沐里纷纷


私信TA

用户名:Epoch

访问量:63675

签 名:

我不会算法

等  级
排  名 37
经  验 12906
参赛次数 1
文章发表 172
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

不会算法

解题思路:

一个单词列表(vector类型)维护单词的种类和顺序,一个单词计数列表(map类型)维护单词计数并确保列表中的单词唯一性,好处是能在接近O(1)的复杂度里完成查找,缺点是内存开销变大了


注意事项:

参考代码:

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <stdio.h>
#include <cctype>

using namespace std;

vector<string> wordList;
map<string, int> wordCount;

void getWordCount(string& s)
{
	string::iterator it1, it2;
	it1 = it2 = s.begin();
	//步出单词
	for (; it2 < s.end(); it2++)
	{
		if (isalpha(*it2))
			continue;//用外面for循环的条件作为守卫条件是安全的
		else
		{
			string temp;
			temp = s.substr(it1 - s.begin(), it2 - it1);
			for (string::iterator i = temp.begin(); i < temp.end(); i++)
				*i = toupper(*i);
			//wordList中还没有该单词
			//if (wordList.end() == find(wordList.begin(), wordList.end(), temp))
			if (0 == wordCount[temp])
			{
				wordCount[temp]++;
				wordList.push_back(temp);
			}
			else
				wordCount[temp]++;
			it1 = it2;
			//迭代器不能访问'\0',一访问就报错...所以这里判断it1的下一个元素
			//步入单词
			while (!isalpha(*it1) && it1 + 1 < s.end())
				it1++;
			it2 = it1;
		}
	}
}

void output()
{
	//获取单词最大长度
	vector<int> wordLen;
	for (vector<string>::iterator it = wordList.begin(); it < wordList.end(); it++)
		wordLen.push_back(it->length());
	int maxLen = *max_element(wordLen.begin(), wordLen.end());

	//cout << maxLen << endl;

	//根据wordList中的顺序输出
	for (vector<string>::iterator it = wordList.begin(); it < wordList.end(); it++)
	{
		int len = it->length();
		int times = wordCount[*it];
		//输出前导空格
		for (int i = 0; i < maxLen - len; i++)
			cout << " ";
		//输出单词和冒号
		cout << *it << ":";
		//输出"*"
		for (int i = 0; i < times; i++)
			cout << "*";
		//输出wordCount中单词个数计数
		cout << times << endl;
	}
}

int main(int argc, char** argv)
{
	string s;
	getline(cin, s);
	getWordCount(s);
	output();
	//system("pause");
	return 0;
}


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区