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:

     1 class Solution {
     2 public:
     3     vector<vector<string> > groupAnagrams(vector<string>& strs) {
     4         vector<vector<string> > result;
     5         if(strs.empty()) return result;
     6         
     7         sort(strs.begin(), strs.end());
     8         unordered_map<string, vector<int> > ht;
     9         
    10         //initialize the hash table
    11         //sort each string and map the same into hash table
    12         for(int i = 0; i < strs.size(); i++){
    13             string temp = strs[i];
    14             sort(temp.begin(), temp.end());
    15             ht[temp].push_back(i);
    16         }
    17         
    18         for(unordered_map<string, vector<int> >::iterator ite = ht.begin(); ite != ht.end(); ite++){
    19             vector<string> temp;
    20             int n = (ite->second).size();
    21             for(int i = 0; i < n; i++){
    22                 temp.push_back(strs[(ite->second)[i]]);
    23             }
    24             result.push_back(temp);
    25         }
    26         return result;
    27     }
    28 };
    [
      ["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.

    Update (2015-08-09):
    The signature of the function had been updated to return list<list<string>> instead of list<string>, as suggested here. If you still see your function signature return a list<string>, please click the reload button  to reset your code definition.

  • 相关阅读:
    20170226-云计算设计模式翻译-自动伸缩指南(逐字翻译)
    20170723-Ioc与AOP
    20170710-几维晨规
    诸城项目-开发日志
    GPS常识-B版(简)
    GPS常识-A版(详)
    20141209-基本概念-BlogEngine.NET(1)-笔记
    9.聚类分析
    7.分类:基本概念 忌讳
    6.挖掘关联规则
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4850595.html
Copyright © 2011-2022 走看看