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;
              
          }
      };
  • 相关阅读:
    AjaxHelper 无刷新留言
    girdview 中的radiobutton 的逐行触发checkedselected事件
    .NET 新语法
    获取checkbox的值
    git 代码提交规范
    chrome的timeline中stalled问题解析
    小程序添加节流阀
    深度遍历与广度遍历
    JS 运行机制
    地址栏输入url后做了那些事情什么
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5114324.html
Copyright © 2011-2022 走看看