1. 程式人生 > >49. Group Anagrams

49. Group Anagrams

container example pub ring 方法 logs put str nat

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note: All inputs will be in lower-case.

很明顯,這個題目要求將字母相同的單詞歸為一組。

判斷字符串中字符相同一般有兩種方法:

  • 使用容器map<char, int>
  • 排序,然後使用=運算符判斷是否相等

具體到本題中,可以將字符串排序後的結果作為key,vector<string>作為value,使用map<key, vector<string>>,每個key對應的vector<string>就是同一組單詞。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        
if (strs.empty()) return res; unordered_map<string, vector<string>> container; for (auto str : strs) { string tmp(str); std::sort(tmp.begin(), tmp.end()); (container[tmp]).push_back(str); }
for (auto ele : container) res.push_back(ele.second); return res; } };

49. Group Anagrams