当前位置:首页 > 编程笔记 > 正文
已解决

力扣学习笔记——49. 字母异位词分组

来自网友在路上 160860提问 提问时间:2023-10-25 08:16:54阅读次数: 60

最佳答案 问答题库608位专家为你答疑解惑

49. 字母异位词分组

https://leetcode.cn/problems/group-anagrams/?envType=study-plan-v2&envId=top-100-liked
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

示例 1:

输入: strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出: [[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
示例 2:

输入: strs = [“”]
输出: [[“”]]
示例 3:

输入: strs = [“a”]
输出: [[“a”]]

这个首先是排序,排序后用哈希表将结果和排序的字符串作为键对应起来

知识点

C++ 排序的库函数使用

在 C++ 中,你可以使用 头文件中的库函数来进行排序。以下是一些常用的排序函数:

std::sort():对容器或指定范围内的元素进行排序,默认按升序排序。注意:std::sort(),不光能对数字进行排序,还可以对字母进行排序。

#include <algorithm>
#include <vector>int main() {std::vector<int> nums = {5, 2, 8, 1, 9};std::sort(nums.begin(), nums.end());// 输出排序后的结果for (const auto& num : nums) {std::cout << num << " ";}return 0;
}

输出结果:1 2 5 8 9

std::stable_sort():与 std::sort() 类似,但保持相等元素的相对顺序不变。

#include <algorithm>
#include <vector>int main() {std::vector<int> nums = {5, 2, 8, 1, 9};std::stable_sort(nums.begin(), nums.end());// 输出排序后的结果for (const auto& num : nums) {std::cout << num << " ";}return 0;
}

输出结果:1 2 5 8 9

自定义排序:你还可以使用自定义的比较函数来进行排序,例如按照特定的条件进行排序。

#include <algorithm>
#include <vector>bool customCompare(int a, int b) {// 自定义排序规则:按照奇偶性进行排序if (a % 2 == 0 && b % 2 != 0) {return false;  // a 在 b 前面} else if (a % 2 != 0 && b % 2 == 0) {return true;   // a 在 b 后面} else {return a < b;  // 其他情况按照升序排序}
}int main() {std::vector<int> nums = {5, 2, 8, 1, 9};std::sort(nums.begin(), nums.end(), customCompare);// 输出排序后的结果for (const auto& num : nums) {std::cout << num << " ";}return 0;
}

输出结果:1 5 9 2 8

这些是一些常用的排序函数和用法。你可以根据实际需求选择适合的排序函数,并根据需要编写自定义的比较函数

如何用for循环如何拿到std::unordered_map的键和值

如果你想使用 for 循环来获取 std::unordered_map 的键和值,你可以使用迭代器来遍历容器。每个迭代器指向一个键值对,你可以通过解引用迭代器来获取键和值。

以下是一个示例代码,展示了如何使用 for 循环遍历 std::unordered_map 并获取键和值:

#include <iostream>
#include <unordered_map>int main() {std::unordered_map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};// 遍历 unordered_mapfor (auto it = myMap.begin(); it != myMap.end(); ++it) {int key = it->first;std::string value = it->second;std::cout << "Key: " << key << ", Value: " << value << std::endl;}return 0;
}

在上面的示例中,我们使用 auto 关键字来推导出迭代器的类型。然后,使用 begin() 函数获取指向第一个键值对的迭代器,使用 end() 函数获取指向最后一个键值对之后位置的迭代器。在循环中,通过解引用迭代器来获取当前键值对的键和值。

输出结果将是:

Key: 1, Value: apple
Key: 2, Value: banana
Key: 3, Value: orange

你可以根据实际需要修改键和值的类型,并在循环中执行适当的操作

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"力扣学习笔记——49. 字母异位词分组":http://eshow365.cn/6-24043-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!