原题链接:蓝桥杯算法提高VIP-统计单词数
蓝桥杯不支持unordered_map
当然可以写一个结构体来自定义规则结合map来实现unordered_map
不过需要reverse正序(下面给出该结构体写法)
不然只好乖乖用vector
看了前面的大佬的题解(我过了后看)
istringstream不香吗?
虽说这个类比较慢,但是照样过
//定义无序map时
//map<string, int, DisableCompare<string> >
//来实现类似unorder_map<string, int>
template <class T>
struct DisableCompare : public binary_function<T, T, bool>
{
bool operator()(T L, T R)const
{
static bool disablecompare = false;
if (L == R)
{
return false;
}
if (disablecompare)
{
disablecompare = false;
return false;
}
else
{
disablecompare = true;
return true;
}
}
};
想必你看到这样结构体可能会头昏
下面给出我AC代码
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <sstream> //提供istringstream类
#include <algorithm>
using namespace std;
struct node {
string str;
int cnt;
node(string str, int cnt = 1) : str(str), cnt(cnt) {}
bool operator==(string s) const {//重置==实现查找结构体某一个元素(48行)
return s == this->str;
}
};
typedef vector<node>::iterator vit;
int main() {
vector<node> a;
string s;
int len = -1;
getline(cin, s);
if (s.empty()) {
return 0;
}
else {
istringstream is(s); //利用istringstream快速分解字符串
while (!is.eof()) {
string t;
is >> t;
if (t.empty()) {
break;
}
if (!isalpha(t[t.size() - 1])) {
//t.pop_back(); //C++11标准,蓝桥杯不支持
t.erase(t.size() - 1); //只好使用erase
}
len = max((int)(t.size()), len);
for (int i = 0; i < t.size(); i++) {
if (islower(t[i])) {
t[i] -= 32;
}
}
vit it = find(a.begin(), a.end(), t);
if (it != a.end()) {
it->cnt++;
}
else {
a.push_back(node(t));
}
}
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < len - a[i].str.size(); j++) {
cout << " ";
}
cout << a[i].str << ':';
for (int j = 0; j < a[i].cnt; j++) {
cout << '*';
}
cout << a[i].cnt << endl;
}
return 0;
}
}
这里多说两句
如果使用istringstream以空格为基准分字符串直接使用>>即可(参考第34行)
如果是其他的则是getline(is, t, "分割字符")
(变量名以上面的代码为准)
刚来这个网站
代码如果有什么不足之处,请指正
9.9 分
3 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复