C++Primer第五版 5.4.1节练习

练习5.14:编写一段程序,从标准输入中读取若干string对象并查找连续重复出现的单词。所谓连续重复出现的意思是:一个单词后面紧跟着这个单词本身。要求记录连续出现的最大次数以及对应的单词。如果这样的单词存在,输出重复出现的最大次数。如果不存在,输出一条信息说明任何单词都没有连续出现过。例如,如果输入是 
how now now now brown cow cow 
那么输出应该表明单词now连续出现了3次

#include <iostream>
#include <string>
#include <vector>
using namespace std;
void main()
{
    string myString, beforeString, maxRepeatString;
    int repeatNum = 0, maxrepeatNum = 0, cinCount = 0;
    bool flag = false;
    while (cin >> myString)
    {
        cinCount++;
        if (myString == beforeString)
        {
            repeatNum++;
            flag = true;
        }
        else
        {
            flag = false;
            repeatNum++;
            if (maxrepeatNum < repeatNum)
            {
                maxrepeatNum = repeatNum;
                if (cinCount == 1)
                {
                    maxRepeatString = myString;
                }
                else
                {
                    maxRepeatString = beforeString;
                }
            }
            beforeString = myString;
            repeatNum = 0;

        }
    }
    //最后一个若相同 不会进入else
    if (flag)
    {
        repeatNum++;
        if (maxrepeatNum < repeatNum)
        {
            maxrepeatNum = repeatNum;
            if (cinCount == 1)
            {
                maxRepeatString = myString;
            }
            else
            {
                maxRepeatString = beforeString;
            }
        }
    }
    cout << maxRepeatString << " occurs " << maxrepeatNum<< (maxrepeatNum > 1 ? " times" : " time") << endl;
}

or

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    string word, wordnext,maxRepeatWord;
    int maxNum = 1, cinCount = 0;

    if (cin >> word)
    {
        cinCount++;
        int wordCnt = 1;
        while (cin >> wordnext)
        {
            cinCount++;
            if (word == wordnext)
                ++wordCnt;
            else
            {

                if (maxNum < wordCnt)
                {
                    maxNum = wordCnt;
                    maxRepeatWord = word;
                }
                word = wordnext;
                wordCnt = 1;
            }
        }
        //最后一个相同 进入不了
        if (maxNum < wordCnt)
        {
            maxNum = wordCnt;
            maxRepeatWord = word;
        }

    }
    if (cinCount == 1)
    {
        maxNum = 1;
        maxRepeatWord = word;
    }
    cout << maxRepeatWord << " occurs " << maxNum << (maxNum > 1 ?" times" : " time" )<< endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/alolf/article/details/81127257
今日推荐