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.
solution:
compare char count between two string
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()) return false;
Map<Character, Integer> count = new HashMap<>();
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(!count.containsKey(c)){
count.put(c, 1);
}else{
int num = count.get(c);
count.put(c, num+1);
}
}
for(int i=0;i<t.length();i++){
char c = t.charAt(i);
if(!count.containsKey(c)){
return false;
}else{
int num = count.get(c);
count.put(c, num-1);
}
}
for(char key:count.keySet()){
if(count.get(key)!=0)
return false;
}
return true;
}
判断字符串是否为字谜

本文提供了一种方法来确定给定的两个字符串是否为字谜,即它们由相同的字符组成,只是排列不同。
646

被折叠的 条评论
为什么被折叠?



