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

        我们可以利用map来解决这个问题。map的key设置为排序后的字符串,value为字符串数组,将每一个排序之后的值为key的字符串加入value这个数组。对于每一个字符串s,复制一个副本str,将str排序后,将s加入map[str]中。然后依次遍历map,将value对应的数组排序之后加入将要返回的result数组中。最后返回result即可。

    1. class Solution {
      public:
          vector<vector<string>> groupAnagrams(vector<string>& strs) {
              unordered_map<string,vector<string>> map;
              for(auto &s: strs){
                  string str(s);
                  sort(str.begin(),str.end());
                  map[str].push_back(s);
              }
              vector<vector<string>> result(map.size());
              int i=0;
              for(auto it=map.begin();it!=map.end();it++,i++){
                  result[i].swap(it->second);
                  sort(result[i].begin(),result[i].end());
              }
              return result;
              
          }
      };
  • 相关阅读:
    CSRF攻击原理
    大前端
    尊敬自己,才能拥有改变的力量
    重温尼采语录 序章
    人生的弹性 -- 观《聚宝盆》有感
    求学梦
    爱国情怀
    雾中见我
    找东西
    走在路上的感悟
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5114324.html
Copyright © 2011-2022 走看看