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.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Solution1:(hashmap count) bucket in this case
Time Complexity: O(N) Space Complexity: O(26)
Solution2:sorting
Time Complexity: O(NlogN) Space Complexity: O(1)
For followup: hashmap or sorting
ref:https://discuss.leetcode.com/topic/39022/the-3-ms-fastest-ac-for-alphabets-and-6-ms-universal-ac-for-unicode-in-java
https://discuss.leetcode.com/topic/94089/java-solution-hashmap-unicode-follow-up
Solution1 Code:
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;
}
}
Solution2 Code:
class Solution2 {
public boolean isAnagram(String s, String t) {
char[] sChar = s.toCharArray();
char[] tChar = t.toCharArray();
Arrays.sort(sChar);
Arrays.sort(tChar);
return Arrays.equals(sChar, tChar);
}
}