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

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 }

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3606671.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值