[LeetCode] Group Anagrams

Group Anagrams

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:

  1. For the return value, each inner list's elements must follow the lexicographic order.
  2. All inputs will be in lower-case.

解题思路:

用hash的方法,将所有的字符分组。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> result;
        
        std::sort(strs.begin(), strs.end());
        
        map<string, vector<string>> codeToStrs;
        for(int i = 0; i<strs.size(); i++){
            codeToStrs[getCode(strs[i])].push_back(strs[i]);
        }
        
        for(map<string, vector<string>>::iterator it = codeToStrs.begin(); it!= codeToStrs.end(); it++){
            result.push_back(it->second);
        }
        
        return result;
    }
    
    string getCode(string s){
        std::sort(s.begin(), s.end());
        return s;
    }
};


展开阅读全文
©️2020 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值