判断两个字符串是否互为变形词
题目要求:
给定两个字符串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;
}
路漫漫其修远兮,最近工作很忙啊,这个系列得加快更新了…