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.

  • 相关阅读:
    PHP header函数设置http报文头示例详解
    在Windows下为PHP安装redis扩展
    CMD模拟http请求
    strstr使用
    memset使用
    QT修改应用程序图标
    纪念下自学QT 第十天 终于写成了串口调试助手
    QT设置textEdit光标到末尾
    QT设置TextEdit颜色
    QT设置QToolBar带有图标和文字
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4850595.html
Copyright © 2011-2022 走看看