《程序员面试金典》(第六版)习题:仅为记录一下以加强印象,不为商业用途,如有侵权请联系删除。以下源码和解释参考了书中源码以及解释。
变位词(Anagrams)是指几个不同的单词,它们每个单词中字符的个数相同,当将每个单词其中每个字符按照ASCII码值升序排列之后,它们变成相同的字符串。比如单词"listen"和单词"silent"互为变位词,因为它们按照ASCII码值升序排列之后都为字符串"eilnst"。算法首先将字符串数组中的每一个字符串其中每个字符按照ASCII码值升序排列,然后将排序后的字符串数组中相同的字符串的原始字符串映射到同一个集合,最后将所有集合中的每一个集合中的所有原始字符串挨着存放到原始数组中即可得到所求。
string sortChars(string s)
{
sort(s.begin(), s.end());
return s;
}
void myStringSort(vector<string> &myArray)
{
unordered_map<string, vector<string>> mapList;
for (string s : myArray)
{
string key = sortChars(s);
if (mapList.find(key) == mapList.end())
{
vector<string> temp;
temp.push_back(s);
mapList.insert({ key,temp });
}
else
{
mapList.at(key).push_back(s);
}
}
int index = 0;
for (auto it = mapList.begin(); it != mapList.end(); it++)
{
vector<string> temp;
temp = it->second;
for (string s : temp)
{
myArray[index] = s;
index++;
}
}
}