• 6-27刷题


    Anagrams

    class Solution {
    public:    
        /**
         * @param strs: A list of strings
         * @return: A list of strings
         */
        vector<string> anagrams(vector<string> &strs) {
            // write your code here
            unordered_map<string, int> hash;
            for (int i = 0; i < strs.size(); ++i) {
                string str = getSortedString(strs[i]);
                if (hash.find(str) == hash.end()) {
                    hash[str] = 1;
                } else {
                    hash[str] += 1;
                }
            }
            vector<string> result;
            for (int i = 0; i < strs.size(); ++i) {
               string str = getSortedString(strs[i]);
                if (hash.find(str) == hash.end()) {
                    continue;
                }
                if (hash[str] > 1) {
                    result.push_back(strs[i]);
                }
            }
            return result;
        }
        
        string getSortedString(const string &str) {
            int count[26];
            memset(count, 0, sizeof count);
            for (int i = 0; i < str.size(); ++i) {
                count[str[i] - 'a']++;
            }
            string sortedStr = "";
            for (int i = 0; i < 26; ++i) {
                for (int j = 0; j < count[i]; ++j) {
                    sortedStr += 'a' + i;
                }
            }
            return sortedStr;
        }
    };
    View Code
  • 相关阅读:
    密码学基础(三)
    密码学基础(二)
    密码学基础(一)
    Lambda代数
    恢复系统
    11.22面试例题
    js中级复习
    11.12
    11.13
    定时器
  • 原文地址:https://www.cnblogs.com/fripside/p/4604868.html
Copyright © 2020-2023  润新知