您的位置:首页 > 其它

count the occurences of anagrams

2013-11-11 01:00 375 查看
// count the occurences of anagrams.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <map>

using namespace std;

int countTheAnagrams(const string &orgString, const string &anagrams)
{
std::map<char, int> hashMap;
std::map<char, int> curMap;

for (int i = 0; i < anagrams.size(); i++)
{
if (hashMap.count(anagrams.at(i)) == 0)
{
hashMap[anagrams.at(i)] = 1;
}
else
{
hashMap[anagrams.at(i)]++;
}
}

int curMatchCount = 0;
int retMatchCount = 0;

for (int i = 0; i < orgString.size(); i++)
{
if (hashMap[orgString.at(i)] != 0)
{
if (curMap.count(orgString.at(i)) == 0)
{
curMap[orgString.at(i)] = 1;
curMatchCount++;
}
else
{
if (curMap[orgString.at(i)] < hashMap[orgString.at(i)])
{
curMap[orgString.at(i)]++;
curMatchCount++;
}
}

if (curMatchCount == anagrams.size())
{
curMatchCount = 0;
retMatchCount++;
curMap.clear();
}
}
}

return retMatchCount;
}

int _tmain(int argc, _TCHAR* argv[])
{

string orgString = "forxxorfxdofr";
string anagrams = "for";

int ret = countTheAnagrams(orgString, anagrams);

printf("ret = %d", ret);

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