1. 题目:
编写一种方法,对字符串数组进行排序,将所有变位词排在相邻的位置。
2. 解题思路:
变位词是指字母相同但排列顺序不同的单词。我们可以通过将每个字符串排序后的结果作为键,来实现变位词的分组和排序。
3. 代码完整实现(C++):
#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
void groupAnagrams(std::vector<std::string>& strs) {
// 使用哈希表存储排序后的字符串作为键,原始字符串列表作为值
std::unordered_map<std::string, std::vector<std::string>> anagramGroups;
// 遍历所有字符串
for (const auto& str : strs) {
std::string sortedStr = str;
// 对字符串进行排序作为键
std::sort(sortedStr.begin(), sortedStr.end());
// 将原始字符串添加到对应键的组中
anagramGroups[sortedStr].push_back(str);
}
// 清空原数组准备重新填充
strs.clear();
// 将分组后的变位词依次放入结果数组
for (const auto& group : anagramGroups) {
for (const auto& str : group.second) {
strs.push_back(str);
}
}
}
int main() {
std::vector<std::string> words = {"eat", "tea", "tan", "ate", "nat", "bat"};
groupAnagrams(words);
for (const auto& word : words) {
std::cout << word << " ";
}
// 可能的输出: eat tea ate tan nat bat (变位词相邻但不保证顺序)
return 0;
}
4. 代码分析:
算法说明
1)时间复杂度:O(n * k log k),其中n是字符串数量,k是字符串的平均长度
- 对每个字符串排序需要O(k log k)时间
- 共有n个字符串
2)空间复杂度:O(n * k),需要存储所有字符串的排序版本和分组结果
3)关键点:
- 使用排序后的字符串作为变位词的统一标识
- 哈希表用于快速查找和分组
- 最后将所有变位词组连续放入结果数组
这种方法保证了所有变位词会被排列在相邻位置,但不同变位词组之间的顺序可能不同。如果需要特定的顺序,可以对哈希表的键进行额外排序。
5. 运行结果:
bat eat tea ate tan nat
感谢您的阅读。原创不易,如您觉得有价值,请点赞,关注。