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;
        }
    };
  • 相关阅读:
    C#实现京东登录密码加密POST
    查询SQL Server数据库所有表字段备注
    DataGridView数值列和日期列
    (转)Android 系统 root 破解原理分析
    Dynamics AX 中重点数据源方法
    .NET中Debug模式与Release模式
    DotNetBar的初步使用
    省市区联动小功能
    多余的Using Namespaces或引用会影响程序的执行效率么?
    MSIL指令集
  • 原文地址:https://www.cnblogs.com/jdneo/p/4750529.html
Copyright © 2011-2022 走看看