zoukankan      html  css  js  c++  java
  • LeetCode OJ: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"]
    ]

    找出同字母的字符群,比较简单的方法就是用map实现,将每个字符排下序作为key就可以了,代码如下:

     1 class Solution {
     2 public:
     3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
     4         vector<vector<string>> ret;
     5         map<string, vector<string>> res;
     6         string tmp;
     7         for(int i = 0; i < strs.size(); ++i){
     8             tmp = strs[i];  //这里是关键
     9             sort(tmp.begin(), tmp.end());
    10             res[tmp].push_back(strs[i]);
    11         }
    12         vector<string> tmpVec;
    13         for(typename map<string, vector<string>>::iterator it = res.begin(); it != res.end(); ++it){
    14             sort(it->second.begin(), it->second.end());
    15         }
    16         for(typename map<string, vector<string>>::iterator it = res.begin(); it != res.end(); ++it){
    17             tmpVec.clear();
    18             if(it->second.size() >= 1)
    19                 for(int i = 0; i < it->second.size(); i++){
    20                     tmpVec.push_back(it->second[i]);
    21                 }
    22             ret.push_back(tmpVec);
    23         }
    24         return ret;
    25     }
    26 };

    还有很多种实现方法实际上,以后再来一一实现  

  • 相关阅读:
    包的使用,json&pickle模块,hashlib模块
    在阿里云购买云服务器并安装宝塔面板
    python 采集斗图啦(多线程)
    python 采集斗图啦xpath
    python 采集唯美girl
    小程序接入内容内容审查接口(图片.文字)
    PEP8规范
    接口的安全问题
    学习redis知识的过程
    Spring葵花宝典
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4943301.html
Copyright © 2011-2022 走看看