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.
呼哈哈哈哈。。。毫无思路。。。本来是想呢。。。遇到一个字母就统计次数。。。复杂性是不是太高。。。
然后又想了,顺序读s中的字符,如果在t中找到,则s和t的对应位同时清零,最后只要看看是不是都是清空了就好了,机智如我。
class Solution {
public:
bool isAnagram(string s, string t) {
int count = 0;
if(s.length() != t.length())
return false;
for(int i = 0;i < s.length();i++)
{
for(int j = 0;j < t.length();j++)
{
if(s[i] == t[j])
{
s[i] = ' ';
t[j] = ' ';
count++;
}
}
}
if(count == s.length())
return true;
return false;
}
};
然后就。。。华丽丽的超时了。。。
后来发现。。。原来题里说你可以假设只有小写。。。噗。。。一口老血。。。那么就是说。。。开一个count[26],s出现的count++,t出现的count–,最后如果count都是0,那么就ok了。
class Solution {
public:
bool isAnagram(string s, string t) {
int count[26] = {0};
if(s.length() != t.length())
return false;
for(int i = 0;i < s.length();i++)
{
count[s[i] - 'a']++;
count[t[i] - 'a']--;
}
for(int i = 0;i < 26;i++)
{
if(count[i] != 0)
return false;
}
return true;
}
};
that’s it