标签:
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.
Solution1:
偷懒做道简单点的。sort再比较,naive。
public class Solution { public boolean isAnagram(String s, String t) { if(s.length()!=t.length()) { return false; } char[] sarr=s.toCharArray(); char[] tarr=t.toCharArray(); Arrays.sort(sarr); Arrays.sort(tarr); for(int i=0;i<sarr.length;i++) { if(sarr[i]!=tarr[i]) { return false; } } return true; } }
Solution2:
用map做了另一种解法,先存s和个数,然后再查t。查看个数是不是小于等于0.
public class Solution { public boolean isAnagram(String s, String t) { if(s.length()!=t.length()) { return false; } Map<Character,Integer> smap=new HashMap<Character,Integer>(); for(int i=0;i<s.length();i++) { if(!smap.containsKey(s.charAt(i))) { smap.put(s.charAt(i),1); } else { int count=smap.get(s.charAt(i)); smap.put(s.charAt(i),++count); } } for(int i=0;i<t.length();i++) { if(!smap.containsKey(t.charAt(i))) { return false; } else { if(smap.get(t.charAt(i))<=0) { return false; } else { int count2=smap.get(t.charAt(i)); smap.put(t.charAt(i),--count2); } } } return true; } }
标签:
原文地址:http://www.cnblogs.com/Machelsky/p/5867584.html