zoukankan      html  css  js  c++  java
  • Leetcode:49. Group Anagrams

    Description

    Given an array of strings, group anagrams together.

    Example

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

    思路

    • 思路一:用map实现,先将每个字符串转换为一个map<char,int>,然后通过一个map<map<char,int>, int> 判断是否重复,然后在此基础上操作
    • 思路二,unordered_map<string,int>实现

    代码

    • map<map<char,int>, int> 实现,102ms
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> res;
            int len = strs.size();
            if(len == 0) return res;
            
            map<map<char, int>, int> Map;
            map<char, int> tmpMap;
            int start = 0;
            for(int i = 0; i < len; ++i){
                tmpMap.clear();
                for(int j = 0; j < strs[i].size(); ++j)
                    tmpMap[strs[i][j]]++;
                    
                if(Map.count(tmpMap) > 0)
                    res[Map[tmpMap]].push_back(strs[i]);
                else{
                    vector<string> strTmp;
                    strTmp.push_back(strs[i]);
                    res.push_back(strTmp);
                    Map.insert(pair<map<char,int>, int>(tmpMap, start));
                    start++;
                }
            }
            
            return res;
        }
    };
    
    • unordered_map <string, int> 实现,39ms
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> res;
            int len = strs.size();
            if(len == 0) return res;
            
            unordered_map<string, int> Map;
            string tmpMap;
            int start = 0;
            for(int i = 0; i < len; ++i){
                tmpMap = strs[i];
                sort(tmpMap.begin(), tmpMap.end());
                //for(int j = 0; j < strs[i].size(); ++j)
                 //   tmpMap[strs[i][j]]++;
                    
                if(Map.count(tmpMap) > 0)
                    res[Map[tmpMap]].push_back(strs[i]);
                else{
                    vector<string> strTmp;
                    strTmp.push_back(strs[i]);
                    res.push_back(strTmp);
                    Map.insert(pair<string, int>(tmpMap, start));
                    start++;
                }
            }
            
            return res;
        }
    };
    
  • 相关阅读:
    Beans
    HDU2830
    HDU1176
    rtc关机闹钟7 jni层 com_android_server_AlarmManagerService
    rtc关机闹钟6 AlarmManagerService研究
    rtc关机闹钟5 AlarmManager研究
    数论学习_裴蜀定理
    hdu-5465-二维BIT+nim
    hdu-1892-二维BIT
    hdu-2227-dp+bit
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6848289.html
Copyright © 2011-2022 走看看