题目如下:
对于两个字符串A和B,如果A和B中出现的字符种类相同且每种字符出现的次数相同,则A和B互为变形词,请设计一个高效算法,检查两给定串是否互为变形词。
给定两个字符串A和B及他们的长度,请返回一个bool值,代表他们是否互为变形词。
测试样例:
"abc",3,"bca",3
返回:true我的代码:
#include<iostream>
#include<string>
#include<map>
using namespace std;
bool chkTransform(string A, int lena, string B, int lenb) {
// write code here
if(lena!=lenb)return false;
map<char,int>mapA;
map<char,int>::iterator itorA;
map<char,int>mapB;
map<char,int>::iterator itorB;
for(int i=0;i<A.length();i++)
{
char s=A[i];
itorA=mapA.find(s);
if(itorA!=mapA.end())
{
itorA->second++;
}
else
{
mapA.insert(pair<char,int>(s,1));
}
}
for(int i=0;i<B.length();i++)
{
char s=B[i];
itorB=mapB.find(s);
if(itorB!=mapB.end())
{
itorB->second++;
}
else
{
mapB.insert(pair<char,int>(s,1));
}
}
itorA=mapA.begin();
itorB=mapB.begin();
while(itorA!=mapA.end())
{
char s=itorA->first;
itorB=mapB.find(s);
if(itorB!=mapB.end())
{
if(itorB->second==itorA->second)
{
}
else
{
return false;
}
}
else
{
return false;
}
itorA++;
}
return true;
}
主要用到了STL中的map来实现功能。接下来我会总结一下map的用法和hashmap的用法。