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?
网上找到的最简单的解决方法如下:
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));
}
}
自己想到的方法为使用两个Map,对比每一个key的value值,但这种方法在一个特定的50000字符组成的字符串的对比时出现错误,正在寻找原因。
代码如下:
package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Solution {
public static void main(String []args){
String s1 = "";
String s2 = "";
System.out.println(isAnagram(s1,s2));
}
public static 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;
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);
}
}
if(hm.size()!=hm1.size())
return false;
for(char c:hm.keySet()){
if(!hm1.containsKey(c))
return false;
else if(hm1.get(c)!=hm.get(c))
return false;
}
return true;
}
}