LeetCode 49. 字母异位词分组(Group Anagrams)

题目描述

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

说明:

  • 所有输入均为小写字母。
  • 不考虑答案输出的顺序。

解题思路

利用哈希的思想解题。构造一个字符串到字符串集合的映射数组map,对于每一个字符串,首先对其按字典序从小到大排序,这样有相同字母的异位词就可以映射为同一字符串,然后在map中找到对应的集合并添加原字符串。遍历完给定的字符串数组后,再依次把map中的分组添加到结果集合中。

代码

 1 class Solution {
 2 public:
 3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
 4         vector<vector<string>> res;
 5         map<string, vector<string>> strToVec;
 6         for(string str: strs){
 7             string emp = str;
 8             sort(emp.begin(), emp.end());
 9             strToVec[emp].push_back(str);
10         }
11         for(auto iter: strToVec)
12             res.push_back(iter.second);
13         return res;
14     }
15 };

猜你喜欢

转载自www.cnblogs.com/wmx24/p/9135817.html