前言
hash表(或称散列表),想学很久了。知道这个原理,但是一直没有具体地应用或者实现过。
这道题目的tags有hash table,当然我用的也算是hash table,但是感觉还是差点事情。
Solution提交后beats 53%的Solution,应该还有更好的答案。
题目
Acceptance: 42%, Difficulty: Easy
Give two strings s and t, write a function to determine if t is an an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “cat”, return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters ? How would you adapt your solution to such case?
Tags Hash Table Sort
题解
nagaram是颠倒的意思,这里可以理解为乱序。也就是说只要s 和t 中每个字母的个数是一致的,返回true。否则返回false。
思路很简单,申请两个26大小的数组,每个位置对应着26个字母。遍历 s ,对s 中所有的字母统计;遍历t, 对t 中所有字母统计。然后对着两个数组中每个数字的大小是否一致。有任一对应的int不一致即返回false。
AC Code
class Solution
{
public:
bool isAnagram(string s, string t)
{
int schar[26] = {0};
for (int i = 0; i < s.size(); i++)
schar[s[i] - 'a']++;
int tchar[26] = {0};
for (int i = 0; i < t.size(); i++)
tchar[t[i] - 'a']++;
for (int i = 0; i < 26; i++)
if (schar[i] != tchar[i])
return false;
return true;
}
};
Follow up
当输入为Unicode character时。
特意查了一下,Unicode(统一码,万国码,单一码),共65536个码位,现有1114112个。如果要申请这么多个空间的int数组而其中又有大片值为0,显然不合适。
那么是不是可以借助STL中map,或者借助其思想,生成一个s.size()*2 大小的二维数组,每行第一列存储Unicode码,第二列存储它出现的次数。
由此又能反推回原题,原题需要申请26个int的数组吗?是不是申请 s.size() * 2 的一个二维数组即可?
Discussion
来看Discussion,看到了一种思路可以修改我的代码。修改后的大致代码如下:
if(s.size() != t.size()) return false;
int charCnt[26] = 0;
for (int i = 0; i < s.size(); i++)
{
charCnt[s[i] - 'a']++;
charCnt[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++)
if (charCnt[i])
return false;
return true;
然后,看 到了一种更好的思路,可以把上面的循环部分改为如下:
int cnt = 0;
int charCnt[127] = {0};
for (int i = 0; i < s.size(); i++)
{
if(++charCnt[s[i]] == 1) cnt++;
if(--charCnt[t[i]] == 0) cnt--;
}
return cnt == 0;
如此修改之后,代码运行时间12ms,列入了速度中的第一列。
最后这种方法很巧妙。利用cnt来计数,每当s中的一个字母出现(即 == 1),那么就使标记cnt自加1,无论这个字母出现多少次,当t 中出现一次这个字母,就使它所在的int自减一次,当t 中出现了s 中这个字母同样多次数的这个字母后。(即 == 0),那么标记cnt–。这样。如果s 中比t 中多一个或几个字母的话,cnt将不为0。
可能会想到,包括我也想到,如果t 中有,而s 中没有,即( == -1) 的情况怎么考虑呢?
其实以上代码是考虑了的。当t 中有 s 里没有的字母的时候,并且t 和s 的size()又是一样大的,那么s 中必有字母是t 所没有或个数不到s 中的个数的。
以上有点绕,大家慢慢想。