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;
        }
    };
    
  • 相关阅读:
    mysql timestamp字段定义的
    mybatis的Selective接口和普通接口的区别
    intllij IDE 中git ignore 无法删除target目录下的文件
    maven的单元测试中没有
    java volatile关键字
    RestExpress response中addHeader 导致stackOverflow
    log4j配置后行号乱码显示为?问号
    软件研发人员的职业发展规划
    CPU与内存互联的架构演变
    windows系统安装
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6848289.html
Copyright © 2011-2022 走看看