创建两个数组存储字母的个数,再对比两个数组是否相同
代码:
public class Solution { public boolean isAnagram(String s, String t) { int[] alphabets1 = new int[26]; int[] alphabets2 = new int[26]; if(s.length() != t.length()) return false; for(int i = 0; i < s.length(); i++){ alphabets1[(int) (s.charAt(i)-‘a‘)]++; } for(int i = 0; i < t.length(); i++){ alphabets2[(int) (t.charAt(i)-‘a‘)]++; } for(int i = 0; i < 26; i++){ if(alphabets1[i] != alphabets2[i]) return false; } return true; } }
Jan 12 - Valid Anagram; Hash Table; Sort; Alphabets; String;
原文:http://www.cnblogs.com/5683yue/p/5126493.html