題目
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.
解法
和387題類似,都可以使用統計每個字符出現的個數的方式來比較,只要所有字符出現的次數相同且兩個字符串不行等,則返回true。需要注意的是,根據leetcode的評價標準,兩個空串返回true。
public boolean isAnagram(String s, String t) {
int lenS = s.length();
int lenT = t.length();
if (lenS == 0 && lenT == 0) return true;
if (lenS == 1 && lenT == 1 && s.equals(t)) return true;
if (lenS != lenT) return false;
if (s.equals(t)) return false;
int[] recordS = new int[26];
int[] recordT = new int[26];
for (int i = 0; i < lenS; i++) {
char c1 = s.charAt(i);
char c2 = t.charAt(i);
int index1 = c1 - 'a';
int index2 = c2 - 'a';
recordS[index1]++;
recordT[index2]++;
}
for (int i = 0; i < 26; i++)
if (recordS[i] != recordT[i])
return false;
return true;
}
擴展
如果需要加入unicode字符,那麼上一種方式就不可行,因爲小寫字母只有26個,但unicode字符有6萬多個,使用數組來一一對應開銷過大。這時就可以使用hashmap來存儲鍵值對,因爲hashmap自動去重,可以參考我的上一篇博客.