題目:Given two stringssandt, write a function to determine iftis an anagram ofs.
For example,
s= "anagram",t= "nagaram", return true.
s= "rat",t= "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
解題思路:分別統計s和t的每個字母的個數,如果均相同則為Anagram。
示例代碼:
packagecom.test.demo; /** *@author徐劍 *@Time2015-01-18 */ publicclassSolution { publicbooleanisAnagram(Strings,Stringt) { int[]s_num=fun(s); int[]t_num=fun(t); for(inti=0;i { if(s_num[i]!=t_num[i]) { returnfalse; } } returntrue; } /** *初始化一個長度為26的數組,初始值為0,代表a-z的個數 *@paramstr *@return */ privateint[]fun(Stringstr) { intnum[]=newint[26]; for(inti=0;i { intk=Integer.valueOf(str.charAt(i)).intValue()-97; num[k]++; } returnnum; } }