L2-050 懂蛇语
解题思路
这是一道比较简单的字符串处理的题目,考点就是对于单词间有多个空格的字符串的处理,还有对字符串的排序。
方法一: 记录一下上个字符的状态,如果上一个是空格(初始化为true),而当前的是字符,那就说明它是一个单词的开头。用一个map<string,vector
补充一个知识点,map和unordered_map,前者支持pair作为key,但是后者不支持。
方法二: 使用字符串流,不过这种写法相对于方法一并没有短多少。这里给出的是方法二的代码
ac✅️代码
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<map>
#include<algorithm>
using namespace std;
string get_feature(string sentence)
{
string feature = "";
stringstream ss(sentence);
string word;
while(ss >> word)
{
feature += word[0];
}
return feature;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n; cin >> n;
string dummy;
getline(cin, dummy);
map<string, vector<string>> dict;
for(int i = 0 ; i < n ; i++)
{
string sentence;
getline(cin, sentence);
string feature = get_feature(sentence);
dict[feature].push_back(sentence);
}
int k;
cin >> k;
getline(cin, dummy);
while(k--)
{
string query;
getline(cin, query);
string f = get_feature(query);
auto it = dict.find(f);
if(it != dict.end())
{
//引用
vector<string>& res = it->second;
sort(res.begin(), res.end());
for(int i = 0; i < res.size(); i++)
{
if(i != res.size() - 1)
{
cout << "|";
}
}
cout << "\n";
}
else
{
cout << query << "\n";
}
}
return 0;
}

浙公网安备 33010602011771号