《Cracking the Coding Interview》——第1章:数组和字符串——题目3
2014-03-18 01:36
513 查看
2014-03-18 01:32
题目:对于两个字符串,判断它们是否是Anagrams。
解法:统计俩单词字母构成是否相同即可。
代码:
题目:对于两个字符串,判断它们是否是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; }
相关文章推荐
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目2
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目4
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目5
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目6
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目7
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目8
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目1
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目1
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目8
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目7
- 《Cracking the Coding Interview》——第14章:Java——题目6
- 《Cracking the Coding Interview》——第17章:普通题——题目1
- 《Cracking the Coding Interview》——第17章:普通题——题目7
- 《Cracking the Coding Interview》——第17章:普通题——题目14
- Cracking the Coding Interview 题目分析笔记—— Array and String
- 《Cracking the Coding Interview》——第3章:栈和队列——题目6
- 《Cracking the Coding Interview》——第5章:位操作——题目4
- crack the coding interview 数组与字符串 1.5
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目9
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目2