重复单词计数

输入一行字符串,统计重复单数个数,并显示重复单词,和个数。

example:
input :SHE she laughed he he because he a student student student.
output: he 3
       student 2
       

客户分析:
分解问题:
输入
sort
重复单词计数并输出

采用的存储数据结构:vector

子问题分别求解:
输入

vector<string> words;
for(string temp;cin>>temp;)
  words.push_back(temp);
  //while (cin >> temp)// {
		//words.push_back(temp);
	//}
	words.push_back("z");//安排一个哨兵进行触发

按照单词首字母顺序sort

sort(words.begin(), words.end());

重复单词计数并输出

int numberofword = 1;
	string previous = "";
	string current;
	for (int i = 0; i < words.size(); ++i)
	{
		
		current = words[i];
		if (current == previous)
		{
			++numberofword;
		}
		else if (numberofword > 1)
		{
			cout << "word: " << previous << " " << numberofword << endl;
			numberofword = 1;
		}
		
		previous = current;
	}

子问题合并:

vector<string> words;
	//for (string temp; cin >> temp;)
		//words.push_back(temp);
	string temp;
	while (cin >> temp) {
		words.push_back(temp);
	}
	words.push_back("z");
	sort(words.begin(), words.end());
	int numberofword = 1;
	string previous = "";
	string current;
	for (int i = 0; i < words.size(); ++i)
	{
		
		current = words[i];
		if (current == previous)
		{
			++numberofword;
		}
		else if (numberofword > 1)
		{
			cout << "word: " << previous << " " << numberofword << endl;
			numberofword = 1;
		}
		
		previous = current;
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值