2014-03-18 01:32
题目:对于两个字符串,判断它们是否是Anagrams。
解法:统计俩单词字母构成是否相同即可。
代码:
1 // 1.3 Given two strings, write a method to decide if one is a permutation of the other. 2 // count them. 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 7 class Solution { 8 public: 9 bool isPermutation(const char *s, const char *p) { 10 if (nullptr == s || nullptr == p) { 11 return false; 12 } 13 14 size_t len = strlen(s); 15 if (len != strlen(p)) { 16 return false; 17 } 18 19 int a[256]; 20 memset(a, 0, 256 * sizeof(int)); 21 22 size_t i; 23 for (i = 0; i < len; ++i) { 24 ++a[s[i]]; 25 --a[p[i]]; 26 } 27 for (i = 0; i < 256; ++i) { 28 if (a[i]) { 29 return false; 30 } 31 } 32 return true; 33 } 34 }; 35 36 int main() 37 { 38 char s[1000], p[1000]; 39 Solution sol; 40 41 while (scanf("%s%s", s, p) == 2) { 42 printf("\"%s\" is ", s); 43 if (!sol.isPermutation(s, p)) { 44 printf("not "); 45 } 46 printf("a permutation of \"%s\".\n", p); 47 } 48 49 return 0; 50 }