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;
        }
    };
  • 相关阅读:
    缓存
    mybatis(ibatis)理解
    hibernate理解
    linux vi 命令
    Activity中ConfigChanges属性的用法
    sendStickyBroadcast和sendStickyOrderedBroadcast
    广播 BroadCastReceiver
    Android四大基本组件介绍与生命周期
    ubuntu14.04 开机自动运行应用程序
    Android中BindService方式使用的理解
  • 原文地址:https://www.cnblogs.com/jdneo/p/4750529.html
Copyright © 2011-2022 走看看