您的位置:首页 > 其它

《Cracking the Coding Interview》——第1章:数组和字符串——题目3

2014-03-18 01:36 513 查看
2014-03-18 01:32

题目:对于两个字符串,判断它们是否是Anagrams

解法:统计俩单词字母构成是否相同即可。

代码:

// 1.3 Given two strings, write a method to decide if one is a permutation of the other.
// count them.
#include <cstdio>
#include <cstring>
using namespace std;

class Solution {
public:
bool isPermutation(const char *s, const char *p) {
if (nullptr == s || nullptr == p) {
return false;
}

size_t len = strlen(s);
if (len != strlen(p)) {
return false;
}

int a[256];
memset(a, 0, 256 * sizeof(int));

size_t i;
for (i = 0; i < len; ++i) {
++a[s[i]];
--a[p[i]];
}
for (i = 0; i < 256; ++i) {
if (a[i]) {
return false;
}
}
return true;
}
};

int main()
{
char s[1000], p[1000];
Solution sol;

while (scanf("%s%s", s, p) == 2) {
printf("\"%s\" is ", s);
if (!sol.isPermutation(s, p)) {
printf("not ");
}
printf("a permutation of \"%s\".\n", p);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐