您的位置:首页 > 其它

LeetCode242 Valid Anagram

2017-02-16 12:58 183 查看

题目

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自动去重,可以参考我的上一篇博客.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode