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?
一刷
题解:统计character频率即可。
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;
}
}
拓展:如果为unicode,可以先将字符串sort之后再比较两个字符串是否相等
二刷
词频统计
public class Solution {
public boolean isAnagram(String s, String t) {
int[] freq = new int[26];
for(int i=0; i<s.length(); i++) freq[s.charAt(i) - 'a']++;
for(int j=0; j<t.length(); j++){
freq[t.charAt(j) - 'a']--;
if(freq[t.charAt(j) - 'a']<0) return false;
}
for(int f : freq){
if(f!=0) return false;
}
return true;
}
}