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

     
    Medium

    Given an array of strings, group anagrams together.

    Example:

    Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
    Output:
    [
      ["ate","eat","tea"],
      ["nat","tan"],
      ["bat"]
    ]

    Note:

    • All inputs will be in lowercase.
    • The order of your output does not matter.

    字符串排序,当key

     1 class Solution:
     2     def groupAnagrams(self, strs):
     3         """
     4         :type strs: List[str]
     5         :rtype: List[List[str]]
     6         """
     7         d = {}
     8         for s in strs:
     9             key = ''.join(sorted(s))
    10             
    11             if key in d:
    12                 d[key].append(s)
    13             else:
    14                 d[key] = [s]
    15         res = []
    16         for key in d:
    17             res.append(d[key])
    18         return res

    c++:

     1 class Solution {
     2 public:
     3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
     4         vector<vector<string>> res ;
     5         unordered_map<string,vector<string>> d ;
     6         for(string& s :strs){
     7             string key = s;
     8             sort(key.begin(),key.end());
     9             d[key].push_back(s);
    10         }
    11         for(auto &item :d)
    12             res.push_back(item.second);
    13         return res;
    14     }
    15 };
  • 相关阅读:
    java 运算
    java String
    java的数据类型
    Python: str() 和 repr() 的区别
    Linux命令:which
    Linux命令:locate
    Linux命令:ifconfig
    Linux命令:whereis
    Linux命令:rz 和 sz
    Linux命令:scp
  • 原文地址:https://www.cnblogs.com/zle1992/p/10156774.html
Copyright © 2011-2022 走看看