深信服:输入一个字符串,帮忙统计字符串里面的每个单词出现的次数,以及非法单词的次数。非法单词的定义为:包含数字(0-9)的单词

版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/82810049

深信服2018秋招笔试题:

输入一个字符串,帮忙统计字符串里面的每个单词出现的次数,以及非法单词的次数。非法单词的定义为:包含数字(0-9)的单词

输入一个字符串,长度小于1000,输入的字符仅包含(0-9,a-z,A-Z, . , : ! )及空格。

输出按单词的字母进行排序,每行为 :

单词    单词出现次数

最后一行输出非法单词个数


实例1:

输入:

wow! Is wonderful!

输出:

Is 1

wonderful 1

wow 1

0


实例2:

输入:

abc bcd2 fe fe a3xd

输出:

abc 1

fe 2

2


代码如下:

#include<iostream>
#include<map>
#include<string>
#include<vector>

using namespace std;
int main()
{
	string str;
	map<string, int>temp;
	getline(cin, str);
	int plow = 0, phigh = 0;
	string s = "";
	while (phigh < str.length())
	{
		if (str[phigh] == ' ')
		{
			phigh++;
			plow = phigh;
			temp[s]++;
			s = "";
			continue;

		}
		else
		{
			s = s + str[phigh];
			if (phigh == str.length() - 1) temp[s]++;
			phigh++;
		}

	}
	vector<string>res;
	auto j = temp.begin();
	while(j != temp.end())
	{
		string tmp = j->first;
		int len = tmp.size();
		for (int i = 0; i < len; i++)
		{
			if (!(tmp[i] >= 65 && tmp[i] <= 90 || tmp[i] >= 97 && tmp[i] <= 122))
			{
				if (tmp[i] >= 48 && tmp[i] <= 57)
				{
					res.push_back(tmp);
					j = temp.erase(j);
					j--;
					break;
				}

			}
			else if (tmp[len-1] == 44 || tmp[len-1] == 46 || tmp[len-1] == 58 || tmp[len-1] == 33) {
				string new_tmp(tmp.begin(), tmp.end() - 1);
				int b = j->second;
				temp.insert(make_pair(new_tmp, b));
				j = temp.erase(j);
				j--;
				break;
			}
		}
		j++;
	}
	for (auto s = temp.begin(); s != temp.end(); s++)
	{
		cout << s->first << " " << s->second << endl;
	}
	cout << res.size() << endl;

	system("pause");
    return 0;
}

主要是对问题的仔细分析!然后就是注意细节,特别是迭代器的失效问题,位置变换等问题!

猜你喜欢

转载自blog.csdn.net/Fly_as_tadpole/article/details/82810049