Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
解法一: sort!
public class Solution { public boolean isAnagram(String s, String t) { char[] schar = s.toCharArray(); char[] tchar = t.toCharArray(); Arrays.sort(schar); Arrays.sort(tchar); s = new String(schar); t = new String(tchar); return s.equals(t); } }
解法二:hashmap
import java.util.*; public class Solution { public boolean isAnagram(String s, String t) { if(s.length()!=t.length()) return false; Hashtable<Character, Integer> theTableS = new Hashtable<Character, Integer>(), theTableT = new Hashtable<Character, Integer>(); for (char i:s.toCharArray()) { if (theTableS.containsKey(i)) theTableS.put(i,theTableS.get(i)+1); else theTableS.put(i,1); } for (char i:t.toCharArray()) { if (theTableT.containsKey(i)) theTableT.put(i,theTableT.get(i)+1); else theTableT.put(i,1); } return theTableT.equals(theTableS); } }
解法三:O(n) time, O(1) space
public class Solution { public boolean isAnagram(String s, String t) { int[] alphabet = new int[26]; for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++; for (int i = 0; i < t.length(); i++) alphabet[t.charAt(i) - 'a']--; for (int i : alphabet) if (i != 0) return false; return true; } }