问题描述:写出一个函数 anagram(s, t)
去判断两个字符串是否是颠倒字母顺序构成的
变位词,我的理解就是两个单词都含有m种字符,并且每个字符的个数都相同,我的思路是维护一个字符数组,初始化各项为0,首先统计单词W1的各个字符出现的次数。然后对于单词W2,在字符数组中减去各个字符出现的次数,最后,如果字符数组中存在不为0的项,两个词就不是变位词,否则是变位词,假设两个单词的平均长度为m,那么时间复杂度为o(m)。不过需要额外的26个int空间。代码如下:
</pre><pre name="code" class="cpp">#include <stdio.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <windows.h>
using namespace std;
class Solution {
public:
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
bool anagram(string s, string t) {
// write your code here
int sLen = s.size();
int tLen = t.size();
if (sLen != tLen)
{
return false;
}
transform(s.begin(), s.end(), s.begin(), ::tolower);
transform(t.begin(), t.end(), t.begin(), ::tolower);
int letterStr[26] = {0};
for (int i = 0; i < sLen; i++)
{
if (s.at(i) == ' ')
{
continue;
}
if (s.at(i) < 'a' || s.at(i) > 'z')
{
return false;
}
letterStr[s.at(i) - 'a']++;
}
for (int j = 0; j < tLen; j++)
{
if (t.at(j) == ' ')
{
continue;
}
if (t.at(j) < 'a' || t.at(j) > 'z')
{
return false;
}
letterStr[t.at(j) - 'a']--;
}
for (int k = 0; k < 26; k++)
{
if (letterStr[k])
{
return false;
}
}
return true;
}
};
int main(void)
{
Solution solution;
cout <<solution.anagram("ab", "ab")<<endl;
system("pause");
return 0;
}
当然,我觉得这个题目也可以首先对两个字符串进行快速排序,然后比较两个字符串,如果相同,说明是变位词,否则不是,时间复杂度为m*o(log(m)),效率稍微差点。