zoukankan      html  css  js  c++  java
  • LeetCode 49. Group Anagrams

    https://leetcode.com/problems/group-anagrams/description/

    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: All inputs will be in lower-case.

    • 字符串处理简单题,复习下vector,map的使用
    • 主要是利用STL sort得到唯一的key,就可以做hash映射了
    • Solution里提供了两种方法解决,可以比较看下
      • https://leetcode.com/articles/group-anagrams/
    • unordered_map::unordered_map - C++ Reference
      • http://www.cplusplus.com/reference/unordered_map/unordered_map/unordered_map/
    • vector::push_back - C++ Reference
      • http://www.cplusplus.com/reference/vector/vector/push_back/
     1 //
     2 //  main.cpp
     3 //  LeetCode
     4 //
     5 //  Created by Hao on 2017/3/16.
     6 //  Copyright © 2017年 Hao. All rights reserved.
     7 //
     8 
     9 #include <iostream>
    10 #include <cstring>
    11 #include <vector>
    12 #include <unordered_map>    // unordered_map
    13 #include <algorithm>        // sort
    14 using namespace std;
    15 
    16 class Solution {
    17 public:
    18     vector<vector<string>> groupAnagrams(vector<string>& strs) {
    19         unordered_map<string, vector<string>>   group;
    20         
    21         for (auto s : strs) {
    22             string key = s;
    23             sort(key.begin(), key.end());   // Use the STL sort function to get the ordered string as key
    24             group[key].push_back(s);
    25         }
    26         
    27         vector<vector<string>>  result;
    28         
    29         for (auto iter : group) {
    30             result.push_back(iter.second);
    31         }
    32         
    33         return result;
    34     }
    35 };
    36 
    37 int main(int argc, char* argv[])
    38 {
    39     Solution    testSolution;
    40     
    41     vector<string>  sample{"eat", "tea", "tan", "ate", "nat", "bat"};
    42     
    43     vector<vector<string>>  res;
    44     
    45     res = testSolution.groupAnagrams(sample);
    46     
    47     for (auto it : res) {
    48         for (auto str : it) {
    49             cout << str << endl;
    50         }
    51         cout << endl;
    52     }
    53     
    54     
    55     return 0;
    56 }
    View Code
    bat
    
    tan
    nat
    
    eat
    tea
    ate
    
    Program ended with exit code: 0
    View Result
  • 相关阅读:
    winform 计算器
    js 特效代码网址
    js 动图效果
    计算器 练习
    html frameset 练习
    SQL 仓库管理练习题
    数据库存取图片
    数据库查询Database中的表
    面向对象练习
    C#函数与SQL储存过程
  • 原文地址:https://www.cnblogs.com/pegasus923/p/8376468.html
Copyright © 2011-2022 走看看