【Cracking the coding interview】Q1.4(变位词)
2013-12-23 19:43
561 查看
Write a method to decide if two strings are anagrams or not.
写一个函数判断两个字符串是否是变位词。
O(n)的算法,声明个数组来统计出现的次数
写一个函数判断两个字符串是否是变位词。
O(n)的算法,声明个数组来统计出现的次数
#include <iostream> #include <cstring> #include <stdlib.h> using namespace std; bool isAnagram(string x, string y){ if(x==""||y=="") return false; if(x.length()!=y.length()) return false; int count[256]; memset(count,0,sizeof(count));//初始化很重要,不然结果会不对。 for(int i=0;i<x.length();i++){ count[int(x[i])]++; count[int(y[i])]--; } for(int i=0;i<256;i++) if(count[i]!=0) return false; return true; } int main(){ string x="abcde"; string y="edcbax"; cout<<isAnagram(x,y); system("pause"); return 0; }
相关文章推荐
- 【Cracking the coding interview】Q1.8(旋转字符串)
- 【Cracking the coding interview】Q1.1(字符唯一)
- Cracking the coding interview--Q1.1(python的位操作)
- Cracking the coding interview--Q1
- 【Cracking the coding interview】Q1.6(旋转矩阵)
- 【Cracking the coding interview】Q1.7(矩阵置0)
- Cracking The Coding Interview 1.6
- Cracking the coding interview--Q1.6
- Cracking The Coding Interview5.3 暂存
- Cracking the coding interview--Q1.8
- Cracking the coding interview--Q5.1
- cracking the coding interview 中文版
- cracking the coding interview ch1.1
- Cracking the coding interview--Q4.6
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目1
- 《Cracking the Coding Interview》——第13章:C和C++——题目2
- 《Cracking the Coding Interview》——第14章:Java——题目4
- Cracking The Coding Interview 9.3
- 《Cracking the Coding Interview》——第17章:普通题——题目1
- 《Cracking the Coding Interview》——第17章:普通题——题目11