您的位置:首页 > 理论基础 > 数据结构算法

数据结构和算法经典100题-第25题

2015-12-24 09:18 531 查看
判断两个字符串是否互为变形词

题目要求:

给定两个字符串str1和str2,若str1和str2中的字符种类一样,每个字符出现的频率一样,那么str1和str2就互为变形词。

题目分析:

可以先把一个字符串中字符出现的频率统计出来,然后再验证另一个字符串字符出现的频率。

Okay,no code say what?

#include <stdio.h>
#include <string>
#include <iostream>
#include <map>

using namespace std;

bool isDeformation(string &str1,string &str2) {
if (str1.empty() || str2.empty() || str1.size() != str2.size()) {
return false;
}

map<char,int> mapCount;
for (string::iterator i = str1.begin(); i != str1.end(); ++i) {
mapCount[*i]++;
}

for (string::iterator i = str2.begin(); i != str2.end(); ++i) {
mapCount[*i]--;
if (mapCount[*i] < 0)
return false;
}
return true;
}

int main(void) {
string str1("hello");
string str2("eollh");
string str3("hellq");
if (isDeformation(str1,str2)) {
cout<<" str1 & str2 is deformation."<<endl;
} else {
cout<<" str1 & str2 is not deformation."<<endl;
}

if (isDeformation(str1,str3)) {
cout<<" str1 & str3 is deformation."<<endl;
} else {
cout<<" str1 & str3 is not deformation."<<endl;
}
return 0;

}


路漫漫其修远兮,最近工作很忙啊,这个系列得加快更新了…
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息