题目描述
S和T是两个字符串(它们只由小写字母构成),定义S与T相似当且仅当:
1、S和T长度相同。
2、对于任意两个位置i和j,如果Si和Sj相同,那么Ti和Tj相同;如果Si和Sj不同,那么Ti和Tj不同。(Si的含义为字符串S在第i个位置的字符,Ti的含义为字符串T在第i个位置的字符)
与字符串”abca”相似的串有”abca”,”cdac”,”zetz”等,现在给出一个字符串S,输出与之相似的字典序最小的串。
这道题目是用Hash映射贪心的方法解决的。
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main()
{
string str, res;
cin >> str;
unordered_map<char, char> Hash;
int i = 0;
for (auto c : str) {
if (Hash.find(c) == Hash.end())
Hash[c] = 'a' + (i++);
}
for (auto c : str) {
res.push_back(Hash[c]);
}
cout << res << endl;
}