zoukankan      html  css  js  c++  java
  • 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.

    cpp:

    class Solution {
        public:
           vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> result;
            unordered_map<string,multiset<string>> dict;
            for(auto str : strs){
                string s = str;
                sort(s.begin(),s.end());
                dict[s].insert(str);
            }
            for(auto a : dict){
                vector<string> temp(a.second.begin(),a.second.end());
                result.push_back(temp);
            }
            return result;
        }
    };

    python:

    class Solution(object):
        def groupAnagrams(self,strs):
            res = collections.defaultdict(list)
            for s in strs:
                res["".join(sorted(s))].append(s)
            return map(lambda k:sorted(res[k]),res.keys())
  • 相关阅读:
    python 格式化 json输出
    python
    回顾2013
    C扩展Python
    C扩展Python
    Python
    Python interview preparing
    Python用smtplib发送邮件
    Python 安装路径, dist-packages 和 site-packages 区别
    nginx worker_cpu_affinity使用方法
  • 原文地址:https://www.cnblogs.com/wxquare/p/5228897.html
Copyright © 2011-2022 走看看