C++ Primer复习和学习笔记 第六章 语句





/*
编写一个小程序,从标准输入读入一系列 string 对象,寻找连续重复出现的单词。程序应该找出满足以下条件的
单词的输入位置:该单词的后面紧跟着再次出现自己本身。跟踪重复次数最多的单词及其重复次数。输出重复次
数的最大值,若没有单词重复则输出说明信息。例如,如果输入是: how, now now now brown cow cow 则输出应表明“now”这个单词出现了三次。
*/
#include "iostream"//本程序使用栈实现具体的功能  关键是vs.push_back()   vs.pop_back()
#include "vector"
#include "string"

using namespace std;

int main()
{
	vector<string>  vs;
	string str;
	while (cin>>str)
	{
		vs.push_back(str);
	}
	int num_new=1;
	int num_old=0;

	string  str_old;
	string  str_new;

	vector<string>  vs_heap;
	vector<string>::iterator  vs_heap_head=vs.begin();

	for (vector<string>::iterator iter=vs.begin();iter!=vs.end();++iter)
	{
		if (vs_heap.size()==0)
		{
			vs_heap.push_back(*iter);
		}
		else//vs_heap.size()!=0			
		{
			if (vs_heap[vs_heap.size()-1]==*iter)
			{
				vs_heap.push_back(*iter);
				++num_new;
				str_new=*iter;
				
			} 
			else//vs_heap[vs_heap.size()-1]!=*iter
			{
				while (vs_heap.size()!=0)
				{
					vs_heap.pop_back();
					
				}
				num_new=1;
				vs_heap.push_back(*iter);
			}
		}
		if (num_new>num_old)
		{
			num_old=num_new;
			str_old=str_new;
		}
	}

	if (num_old==1)
	{
		cout<<"没有找到相应的重复的元素!"<<endl;
	}
	else//num_old!= 1
	{
		cout<<"重复最多的字符串是"<<str_old<<"--------"<<"重复的次数是"<<num_old<<endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值