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;
        }
    };
    
  • 相关阅读:
    C/C++操作MySQL数据库——增、删、改、查
    Mysql常用命令行大全——转载
    .NET Framework、C#、ASP.NET之间的关系
    委托和事件
    ASP.NET 页生命周期概述
    在SqlServer下增加MySql的链接服务器
    Head First 设计模式----DecoratorPattern
    jquery easyui----tree
    Head First 设计模式----ObserverPattern
    Jquery easyui----combotree
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6848289.html
Copyright © 2011-2022 走看看