如何高效查找一个字符串中,出现次数最多的字符?
1、不允许简单的循环查找;
2、字符串长度大于100000;
3、字符串中可能会有中文;
4、可以使用语言内置函数;
彭格列一代目
11 years, 11 months ago
Answers
C++实现的:
#include <hash_map>
using namespace stdext;
bool find_max_char_count(const wchar_t* str, int len)
{
if(NULL == str || 0 == len)
return false;
if(len < 0)
len = wcslen(str);
wchar_t max_ch=L'\0';
int max_count = 0;
hash_map<wchar_t,int> count_list;
for(int i = 0; i < len && str[i]!=L'\0';i++)
{
wchar_t ch = str[i];
count_list[ch]+=1;
if(count_list[ch] > max_count)
{
max_count = count_list[ch];
max_ch = ch;
}
}
wprintf(L"str:%s\n[%c,%d]\n",str,max_ch,max_count);
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
find_max_char_count(L"fsdfdsfdllllllfdslfdsssssssssss",-1);
return 0;
}
输出结果是:
烤鱼的妖婆
answered 11 years, 11 months ago