1. 程式人生 > 其它 >刷題-力扣-面試題 10.02. 變位片語

刷題-力扣-面試題 10.02. 變位片語

題目連結

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/group-anagrams-lcci
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

題目描述

編寫一種方法,對字串陣列進行排序,將所有變位詞組合在一起。變位詞是指字母相同,但排列不同的字串。

注意:本題相對原題稍作修改

示例:

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

說明:

  • 所有輸入均為小寫字母。
  • 不考慮答案輸出的順序。

題目分析

  1. 根據題目描述,將含有相同字母的字串(變位詞)分組
  2. 對變位詞進行排序後的字串相同,對變位詞進行排序作為雜湊表的鍵,變為詞作為值

程式碼

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        std::vector<std::vector<std::string>> res;
        std::unordered_map<std::string, std::vector<std::string>> map;
        // 遍歷所有字串
        for (std::string str : strs) {
            std::string s = str;
            std::sort(s.begin(), s.end());
            map[s].emplace_back(str);
        }
        for (std::unordered_map<std::string, std::vector<std::string>>::iterator it = map.begin(); it != map.end(); ++it) {
            res.emplace_back(it->second);
        }
        return res;
    }
};