您的位置:首页 > 其它

【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)的算法,声明个数组来统计出现的次数

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: