zoukankan      html  css  js  c++  java
  • LeetCode Anagrams

    struct mystat {
        int idx;
        int cnt[26];
        mystat(int id = 0) {idx = id;}
    };
    
    bool cmp(const mystat &a, const mystat &b) {
        for (int i=0; i<26; i++) {
            if (a.cnt[i] < b.cnt[i]) {
                return true;
            } else if (a.cnt[i] > b.cnt[i]) {
                break;
            } else {
                continue;
            }
        }
        return false;
    }
    
    bool same(const mystat &a, const mystat &b) {
        for (int i=0; i<26; i++) {
            if (a.cnt[i] != b.cnt[i]) return false;
        }
        return true;
    }
    
    class Solution {
    public:
        vector<string> anagrams(vector<string> &strs) {
            vector<string> res;
            vector<mystat> stats;
    
            int len = strs.size();
    
            for (int i=0; i<len; i++) {
                stats.push_back(mystat(i));
    
                for (int j=strs[i].size() - 1; j>=0; j--) {
                    stats.back().cnt[strs[i][j] - 'a']++;
                }
            }
            
            sort(stats.begin(), stats.end(), cmp);
    
            int si = 0;
    
            while (si < len ) {
                int i = si + 1;
                for (; i<len; i++) {
                    if (same(stats[si], stats[i])) {
                        res.push_back(strs[stats[i].idx]);
                    } else {
                        break;
                    }
                }
                if (si + 1 < i) {
                    res.push_back(strs[stats[si].idx]);
                }
                si = i;
            }
            return res;
        }
        
    };

    虽然做出来了,不过写那么长,时间又是150ms+肯定还有什么巧妙的方法。

    简短的版本:

    class Solution {
    public:
        vector<string> anagrams(vector<string>& strs) {
            unordered_map<string, int> count;
            vector<string> res;
            int len = strs.size();
            for (int i=0; i<len; i++) {
                string str = strs[i];
                sort(str.begin(), str.end());
                if (count.count(str) == 0) {
                    count[str] = i;
                } else {
                    if (count[str] >= 0) {
                        res.push_back(strs[count[str]]);
                        count[str] = -1;
                    }
                    res.push_back(strs[i]);
                }
            }
            return res;
        }
    };
  • 相关阅读:
    Attribute+Reflection,提高代码重用
    类型安全的EventHandlerList
    简单一招,使解决方案下的项目版本号统一
    T-SQL 随机返回特定行数据和分页查询
    2013年中国系统架构师大会随想
    C#实现在注册表中保存信息
    滤镜
    蒙版
    图层样式和混合模式
    布尔运算
  • 原文地址:https://www.cnblogs.com/lailailai/p/3871245.html
Copyright © 2011-2022 走看看