首页 > 其他 > 详细

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

时间:2014-03-18 11:56:01      阅读:364      评论:0      收藏:0      [点我收藏+]

2014-03-18 01:32

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

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

代码:

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

《Cracking the Coding Inteview》——第1章:数组和字符串——题目3,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/zhuli19901106/p/3606671.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!