• 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;
        }
    };
  • 相关阅读:
    IGeoDatabaseBridge2.GetLineOfSight
    selenium+python自动化测试--alert弹框
    web页面兼容性测试之browsershots工具使用
    selenium自动化测试之定位大全
    Android adb 命令大全
    接口自动化测试 httprunner+locust+python 安装与实践
    appium-uiautomator2-server-v0.x.x.apk does not exist or is not accessible 报错解决方法
    python基础3
    python1、2实践
    python基础2
  • 原文地址:https://www.cnblogs.com/lailailai/p/3871245.html
Copyright © 2020-2023  润新知