首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

统计接续出现的重复最多的同一单词的个数

2012-11-09 
统计连续出现的重复最多的同一单词的个数C/C++ code#includeiostream#includestringusing namespace s

统计连续出现的重复最多的同一单词的个数

C/C++ code
#include<iostream>#include<string>using namespace std;int main(){    string curstr,prestr,most_time_str;    int curtimes=0,maxtimes=1;    while(cin>>curstr)    {        if(curstr==prestr)        {            ++curtimes;        }        else        {            if(curtimes>maxtimes)                {                    maxtimes=curtimes;                    most_time_str=curstr;                }            curtimes=1;        }        prestr=curstr;    }    if(maxtimes!=1)    cout<<"maxtimes="<<maxtimes<<endl;}


问题是:如果连续出现次数最多的单词是在输入流的末尾则无法计数,请问怎么解决。比如输入1 1 2 2 2 则显示maxtimes=2 而正确结果应该是maxtimes=3.

[解决办法]
C/C++ code
#include <iostream>#include <string>using namespace std;int staticsNum(char *pStr){    int length = (int)strlen(pStr);    int count = 1;    int max = 0;    for(int i=0;i<length-1;i++)    {        if(pStr[i]==pStr[i+1])        {            count ++;            if(i+2 == length)                max = count;        }        else        {            if(max<count)                max = count;            count = 1;        }    }    return max;}int main(){    for(int i = 0; i < 50; i++)    {        string str;        cin>>str;        char *pt = (char *)str.c_str();        int MaxNum = staticsNum(pt);        cout<<MaxNum<<endl;    }    return 0;}
[解决办法]
循环后面再做一次比较不就ok??

热点排行