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

    提示:

    此题的关键就是如何将所有anagrams word归类起来。举例来说,比如"ate", "eat","tea"三个单词,若按照字母顺序排序后,都将变为"aet"。因此我们可以对每个单词的字母进行排序,然后利用哈希表对他们进行归类。

    代码:

    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> result;
            int size = strs.size();
            if (size == 0) return result;
            unordered_map<string, int> unmap;
            string tmp;
            
            for (int i = 0; i < size; ++i) {
                tmp = strs[i];
                // 对每个单词,按照字母顺序排序
                sort(tmp.begin(), tmp.end());
                // 如果哈希表中没有出现过,则在哈希表中记录下这一类型单词插入到vector中的索引号
                if (unmap.find(tmp) == unmap.end()) {
                    unmap[tmp] = result.size();
                    result.push_back(vector<string>(1, strs[i]));
                } else {
                    result[unmap[tmp]].push_back(strs[i]);
                }
            }
            // 一次对每一个子vector中的单词进行排序。
            for (int i = 0; i < result.size(); ++i) {
                sort(result[i].begin(), result[i].end());
            }
            return result;
        }
    };
  • 相关阅读:
    函数的节流和函数的防抖
    微信小程序开发
    当后端人员未提供接口,前端人员该怎么测试 --mock
    vue之写发表评论思路
    vue之头像管理思路
    numpy 索引切片迭代
    numpy 通用函数
    numpy 数组运算
    numpy 创建数组
    numpy 数据类型
  • 原文地址:https://www.cnblogs.com/jdneo/p/4750529.html
Copyright © 2011-2022 走看看