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?
第一次用了hashmap理论上来讲时间的效率应该是O(n)的但是代码写得不太简洁,最后导致了时间效率比较低,以及频繁的使用charAt(i)这个方法所耗费的时间是很多的
public class Solution {
public boolean isAnagram(String s, String t) {
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
for(int i = 0 ; i < s.length() ; i++)
{
if(map.containsKey(s.charAt(i)))
map.put(new Character(s.charAt(i)), new Integer(map.get(s.charAt(i))+1));
else
map.put(new Character(s.charAt(i)), new Integer(1));
}
for(int i = 0 ; i < t.length() ; i++ )
{
if(map.containsKey(t.charAt(i))==false)
return false;
if(map.containsKey(t.charAt(i))&&map.get(t.charAt(i))==1)
map.remove(t.charAt(i));
else if(map.containsKey(t.charAt(i))&&map.get(t.charAt(i))>1)
map.put(new Character(t.charAt(i)), new Integer(map.get(t.charAt(i))-1));
}
if(map.size()==0)
return true;
return false;
}
}
但是大体的想法,思路都是对的,于是就在讨论区拿着大神写的精简的代码试了一下,发现用时是40ms
public class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> m = new HashMap<>();
for (Character c : s.toCharArray()) {
int count = m.containsKey(c) ? m.get(c) : 0;
m.put(c, ++count);
}
for (Character c : t.toCharArray()) {
int count = m.containsKey(c) ? m.get(c) : 0;
if (count - 1 == 0) {
m.remove(c);
} else {
m.put(c, --count);
}
}
return m.size() == 0;
}
}
后来又发现使用排序的方法,把字符串排序过后使用equals方法来比较两个字符串是否一样来解决,系统内部的排序是基于比较的排序所以排序的效率理论上来讲应该是O(nlogn)的,但是在这道题中最后测试的结果为使用排序要比使用散列的效果好结果为8ms
public class Solution {
public boolean isAnagram(String s, String t) {
if(t.length() != s.length())
return false;
if(t.length() == 0 && s.length() == 0)
return true;
char[] cs = s.toCharArray();
char[] ts = t.toCharArray();
Arrays.sort(cs);
Arrays.sort(ts);
for(int i = 0; i < cs.length; i++)
{
if(cs[i] != ts[i])
return false;
}
return true;
}
}