[LintCode] Two Strings Are Anagrams
public boolean anagram(String s, String t) { // write your code here s = s.toLowerCase(); t = t.toLowerCase(); int[] count_s = new int[26]; for(int i = 0; i < s.length(); i++){ if(s.charAt(i) == ' ') continue; count_s[s.charAt(i)-'a']++; } int[] count_t = new int[26]; for(int i = 0; i < t.length(); i++){ if(t.charAt(i) == ' ') continue; count_t[t.charAt(i)-'a']++; } int a = hash(count_s); int b = hash(count_t); return a == b; } int hash(int[] count) { int hash = 0; int a = 3; int b = 7; for(int i = 0; i < count.length; i++) { hash = a*hash+count[i]; a = a * b; } return hash; }
Leave A Comment