获取set首个元素值的方法
作用:因为STLset
有自动排序的功能,所以有时需要获取set
的首元素作为字典序最小来进一步处理。
方法:在h.begin()
前面加星号*
即可获取set首个元素的值
set<char> h;
cout << *h.begin();
例题:字符串化繁为简
示例1
输入
()abd
输出
abd
说明
输入字符串里没有被小括号包含的子字符串为"abd",其中每个字符没有等效字符,输出为"abd"。
示例2
输入
(abd)demand(fb)for
输出
aemanaaor
说明
等效字符集为('a','b','d','f'),输入字符串里没有被小括号包含的子字符串集合为 "demandfor",将其中字符替换为字典序最小的等效字符后输出为:"aemanaaor"。
示例3
输入
()happy(xyz)new(wxy)year(t)
输出
happwnewwear
说明
等效字符集为('x','y','z','w'),输入字符串里没有被小括号包含的子字符串集合为"happynewyear",将其中字符替换为字典序最小的等效字符后输出为:"happwnewwear"。
示例4
输入
()abcdefgAC(a)(Ab)(C)
输出
AAcdefgAC
说明
等效字符集为('a','A','b'),输入字符里没有被小括号包含的子字符串集合为"abcdefgAC",将其中字符替换为字典序最小的等效字符后输出为:"AAcdefgAC"。
示例5
输入
never(dont)give(run)up(f)()
输出
devedgivedp
C++代码
// Problem: #OD374. 字符串化繁为简
// Contest: Hydro
// Memory Limit: 256 MB
// Time Limit: 1000 ms
#include <iostream>
#include <set>using namespace std;
using PII = pair<int, int>;int n;
set<char> h; // 存等效字符集
string t; // 存非括号内字符void solve(string &s)
{for (char &x : s){if (h.count(x)) cout << *h.begin(); // 输出set的首元素的值else cout << x;}
}void get(string &s) // 获取等效字符集
{t = "";for (int i = 0; i < n; i++) // 获取字符数量>1的字符集合{if (s[i] == '('){int j = i + 1;string word = "";while (j < n && isalpha(s[j])) word += s[j++];if (word.size() > 1){for (char &x : word) h.insert(x);}i = j;}else if (isalpha(s[i])) t += s[i];}for (int i = 0; i < n; i++) // 检查字符数量=1的字符集合是否含等效字符{if (s[i] == '('){int j = i + 1;if (s[j + 1] == ')'){char x = s[j];if (h.count(tolower(x)) || h.count(toupper(x))){h.insert(x);}}}}
}int main()
{ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);string s;cin >> s;n = s.size();get(s);solve(t);return 0;
}