zoukankan      html  css  js  c++  java
  • [LeetCode] Group Anagrams

    https://leetcode.com/problems/anagrams/

    对每个string求个“hash”,存入hash table,对应的value是group的id。每遇到一个string,用同样的方法计算hash,如果出现过,就加入相应的group;否则,就加入hash table并新开一个group

    /*
     * author  : TK
     * date    : 2017-02-16
     * problem : LeetCode 49. Group Anagrams
     * method  : Hash Table.
     * language: C++
     */
    
    // Compute a hash value of every string and put it into the corresponding group.
    // In the following code, the "hash value" is the lexicographical order of a string.
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector< vector<string> > ret;
            unordered_map<string, int> map;
            int idx = 0;
            for (int i = 0; i < strs.size(); ++i) {
                string str = strs[i];
                sort(str.begin(), str.end());
                if (map.find(str) != map.end()) {
                    ret[map[str]].push_back(strs[i]);
                } else {
                    map[str] = idx++;
                    vector<string> new_vec(1, strs[i]);
                    ret.push_back(new_vec);
                }
            }
            return ret;
        }
    };
    

    由于所有的字母都是小写,上面的排序可以用计数排序优化到O(n)。

    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector< vector<string> > ret;
            unordered_map<string, int> map;
            int idx = 0;
            for (int i = 0; i < strs.size(); ++i) {
                string str = strs[i];
                counting_sort(str);
                if (map.find(str) != map.end()) {
                    ret[map[str]].push_back(strs[i]);
                } else {
                    map[str] = idx++;
                    vector<string> new_vec(1, strs[i]);
                    ret.push_back(new_vec);
                }
            }
            return ret;
        }
    private:
        void counting_sort(string& str) {
            vector<int> number(26, 0);
            for (int i = 0; i < str.size(); ++i) {
                number[str[i] - 'a']++;
            }
            for (int i = 0; i < str.size(); ++i) {
                for (int j = 0; j < 26; ++j) {
                    if (number[j] > 0) {
                        str[i] = (char)('a' + j);
                        number[j]--;
                        break;
                    }
                }
            }
        }
    };
    
  • 相关阅读:
    mysql数据库基本操作sql语言
    asp.net MVC4 表单
    asp.net MVC4 表单
    Mysql字符集设置
    zen Code 支持的代码样式
    sqlserver数据库标注为可疑的解决办法(转)
    SQL Server遍历表的几种方法
    GridView 动态添加绑定列和模板列
    TransactionScope 之分布式配置
    sql server 执行上100mb sql sql sql server 无法执行脚本 没有足够的内存继续执行
  • 原文地址:https://www.cnblogs.com/ilovezyg/p/6405303.html
Copyright © 2011-2022 走看看