zoukankan      html  css  js  c++  java
  • 【Leetcode】【Medium】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.

    解题思路:

    1、对原字符串进行排序,这样所有具有相同字符的字符串就得到了相同的结果。

    2、使用hash表,key是排序后的字符串,value设置为结果数组中保存的地址(下标),这样,找打一个重复字符串就可以直接放入结果数组中。

    注意:

    1、返回结果中,对于相同字符的字符串,要按照字典序进行排序,因此还要多一步排序过程。

    解题步骤:

    1、新建结果数组和hash表;

    2、遍历输入的原始字符串集合,对每个字符串:

      (1)排序

      (2)在hash中查找,如果找到,则取出value,对应到结果数组中,将原字符串插入;

      (3)如果在hash表中没找到,则:

        a. 先在结果二维数组中开辟新的一维数组,用来保存这个新字符组合;

        b. 插入当前这个字符串;

        c.在hash表中添加记录;value值是开辟的新数组位置;

    3、最后遍历结果数组,对每个字数组进行排序;

    AC代码:

     1 class Solution {
     2 public:
     3     vector<vector<string>> groupAnagrams(vector<string>& strs) {
     4         vector<vector<string> > ans;
     5         unordered_map<string, int> mp;
     6 
     7         for (int i = 0; i < strs.size(); ++i) {
     8             string cur(strs[i]);
     9             sort(cur.begin(), cur.end());
    10             if (mp.find(cur) != mp.end()) {
    11                 ans[mp[cur]].push_back(strs[i]);
    12             } else {
    13                 vector<string> tmp(1, strs[i]);
    14                 ans.push_back(tmp);
    15                 mp[cur] = ans.size() - 1;
    16             }
    17         }
    18         
    19         for (int i = 0; i < ans.size(); ++i) {
    20             sort(ans[i].begin(), ans[i].end());
    21         }
    22         
    23         return ans;
    24     }
    25 };
  • 相关阅读:
    Zookeeper入门(三)之工作流
    Zookeeper入门(二)之基础
    Zookeeper入门(一)之概述
    Docker删除/停止容器
    webbench安装和简单使用
    Notepad++ 7.3.2 Download 64-bit x64 / 32-bit x86
    7 常见问题
    6 完整测试
    5 安装Alloc服务
    4 安装MPush
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4771004.html
Copyright © 2011-2022 走看看