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?
使用方法1时,在某的50000字节字符串对比时出现判断错误
代码如下:
public class Solution {
public boolean isAnagram(String s, String t) {
Map<Character,Integer> hm = new HashMap<Character,Integer>();
Map<Character,Integer> hm1 = new HashMap<Character,Integer>();
if(s.length()!=t.length())
return false;
if(s.length()==0)
return true;
for(int i = 0;i < t.length();i++){
if(!hm.containsKey(s.charAt(i))){
hm.put(s.charAt(i), 1);
}
else {
hm.put(s.charAt(i), hm.get(s.charAt(i))+1);
}
if(!hm1.containsKey(t.charAt(i))){
hm1.put(t.charAt(i), 1);
}
else{
hm1.put(t.charAt(i), hm1.get(t.charAt(i))+1);
}
}
for(char c:hm.keySet()){
if(!hm1.containsKey(c))
return false;
else if(hm1.get(c)!=hm.get(c))
return false;
}
return true;
}
}
方法2结果为Accepted:
public class Solution {
public boolean isAnagram(String s, String t) {
char[] sArr = s.toCharArray();
char[] tArr = t.toCharArray();
Arrays.sort(sArr);
Arrays.sort(tArr);
return String.valueOf(sArr).equals(String.valueOf(tArr));
}
}
网上的方法3设置大小为26的Map,仅满足字符串只有小写字母的情况。先将字符串1中的字符记录在map中,再循环字符串2中的字符,每出现一次字符,将map中的值-1,若所有值为0时,则表示两个字符串是由相同字母组成的。