一道c++小编程题,
<span style="font-family: 宋体, Arial, Helvetica, san-serif;">题目:</span> 编写一个小程序,从标准输入读入一系列string对象,寻找连续重复出现的单词,程序应该找出满足以下条件的单词的输入位置:该单词的后面紧跟着再次出现自己本身,跟 踪重复次数量多的单词及其重复次数.输出重复次数的最大值, 例如.如果输入是: how now now now brown cow cow 则输出表明now这个单词出现了三次
本人解法:
#include <iostream> #include <string> #include <cctype> #include <vector> using namespace std; int main() { <pre name="code" class="cpp"><span style="white-space:pre"> </span>string s; vector<string> 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<string>::size_type i = 0; vector<int> 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<int>::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;</pre><pre name="code" class="cpp"><pre name="code" class="cpp"> return 0; }</pre> <pre></pre> <pre></pre> <p>自己的解法答案是对的 但从空间复杂度来说要复杂的多,所以在网上搜了下,寻找到另外一种解决办法,修改后的代码如下:</p> <p></p> <pre name="code" class="cpp">#include <iostream> #include <string> #include <cctype> using namespace std; int main() { </pre><pre name="code" class="cpp"><pre name="code" class="cpp"><span style="white-space:pre"> </span>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; }</pre> <pre></pre> <p></p> <pre></pre> 特在此分享给大家 参考或给予好的想法参考改进。。谢谢~~ <p></p> <p></p> <p><span style="font-family:宋体,Arial,Helvetica,san-serif; font-size:14px; line-height:22.390625px"></span></p> <p><span style="font-family:宋体,Arial,Helvetica,san-serif; font-size:14px; line-height:22.390625px"></span></p> <pre></pre> <pre></pre> </pre></pre>
补充:软件开发 , C++ ,