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.
检查两单词是否为字谜。。主要是两边使用相同类型的字母数目相同。
考虑第一种方法O(n2)复杂度,容易超时
class Solution {
public:
bool isAnagram(string s, string t) {
int size_s = s.size();
int size_t = t.size();
int find = 0;
if(size_s !=size_t) return false;
for(int i=0;i<size_t;i++){
find = 0;
for(int j=0;j<size_s;j++){
if(s[j] == t[i]){
find = 1;
s[j] = '.';
break;
}
}
if(find==0) return false;
}
return true;
}
};
第二种容易想到方案,小写字母总共26中那么将两个单词遍历填表记录单词数目即可O(2n)
class Solution {
public:
bool isAnagram(string s, string t) {
int a[26]={0};
int size = s.size();
for(int i=0;i<size;i++){
a[s[i]-97]++;
}
size = t.size();
for(int i=0;i<size;i++){
a[t[i]-97]--;
}
for(int i=0;i<26;i++){
if(a[i]!=0) return false;
}
return true;
}
};
可以看到暗含限制条件两边长度应当相等,若前面加了这个条件,后面判断记录数组是否小于零即可,
但若没考虑,后面判断条件为数组元素不为零的时候返回false