设为首页 加入收藏

TOP

一道c++小编程题,
2014-11-23 21:46:41 来源: 作者: 【 】 浏览:21
Tags:一道 编程
题目:  
编写一个小程序,从标准输入读入一系列string对象,寻找连续重复出现的单词,程序应该找出满足以下条件的单词的输入位置:该单词的后面紧跟着再次出现自己本身,跟 踪重复次数量多的单词及其重复次数.输出重复次数的最大值,
例如.如果输入是:
how now now now brown cow cow
则输出表明now这个单词出现了三次

本人解法:
#include   
#include   
#include   
#include   
using namespace std;  
int main() { 
    string s;  
    vector vec;  
    int maxRepeat = 0;  
    while (cin >> s){  
        if(ispunct(s[s.size()-1])) s = s.substr(0,s.size() - 1);  //去除最后的标点符号  
        vec.push_back(s);  
    }  
    vector::size_type i = 0;  
    vector vecInt(vec.size(),1);  
    while (i != vec.size() - 1){  
        int j = i;  
        string str = vec[i];  
        while(i != vec.size() - 1)  
        {  
            if(str == vec[++i]) vecInt[j] ++;  
            else break;  
        }  
    }  
    vector::size_type k = 0;  
    int max = vecInt[k];  
    int flag = 0;  
    while (k != vecInt.size() - 1){  
        if(max < vecInt[++k]){  
            max = vecInt[k];  
            flag = k;  
        }  
    }  
    cout << "The word of " <<  vec[flag] << " repeats: " << vecInt[flag] << " times." << endl;  
    cout << endl;
 return 0;  
  
}
  
  

自己的解法答案是对的 但从空间复杂度来说要复杂的多,所以在网上搜了下,寻找到另外一种解决办法,修改后的代码如下:

#include   
#include   
#include   
using namespace std;  
int main() { 
 string nowWord,beforeWord,result;  
    cin >> nowWord;  
    if(ispunct(nowWord[nowWord.size() - 1]))nowWord = nowWord.substr(0,nowWord.size() - 1);  
    result = beforeWord = nowWord;  
    int count = 1,maxCount = 1;  
    while(cin >> nowWord){  
        if(ispunct(nowWord[nowWord.size() - 1]))nowWord = nowWord.substr(0,nowWord.size() - 1);  
        if (beforeWord == nowWord){  
            count++;  
        }  
        else{  
            beforeWord = nowWord;  
            count = 1;  
        }  
        if(count > maxCount){  
            maxCount = count;  
            result = nowWord;  
        }  
    }  
    if(maxCount == 1) cout << "There is no word repeating." << endl;  
    else cout << "The word of " << result << " repeats: " << maxCount << " times." << endl;  
    return 0;  
  
}
  

  
特在此分享给大家 参考或给予好的想法参考改进。。谢谢~~  

  
  
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇博弈问题之SG函数博弈小结 下一篇数组排序 --- 庞果

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·一篇说人话的文章, (2025-12-27 07:50:09)
·Python Web框架哪家 (2025-12-27 07:50:06)
·基于Python的数据分 (2025-12-27 07:50:03)
·深入理解 Java 集合 (2025-12-27 07:22:48)
·Java集合框架全面解 (2025-12-27 07:22:45)