随笔- 509  文章- 0  评论- 151  阅读- 22万 

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 }
复制代码

 

 posted on   zhuli19901106  阅读(460)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示