zoukankan      html  css  js  c++  java
  • LeetCode "Anagrams"

    Problem is, find all values that share the same key value. Similar as another LeetCode problem, hashmap is a good choice.

    http://yucoding.blogspot.com/2012/12/leetcode-quesion-6-anagram.html

    class Solution {
    public:
        string getKey(string str)
        {
            std::sort(str.begin(), str.end());
            return str;
        }
        vector<string> anagrams(vector<string> &strs) {
            unordered_map<string, vector<string>> map;
            
            for (int i = 0; i < strs.size(); i++)
            {
                string k = getKey(strs[i]);
                if (map.find(k) == map.end())
                {
                    vector<string> v; v.push_back(strs[i]);
                    map.insert(make_pair(k, v));
                }
                else
                {
                    map[k].push_back(strs[i]);
                }
            }
    
            vector<string> ret;
            for (auto it = map.begin(); it != map.end(); it++)
            {
                if (it->second.size() >= 2)
                {
                    ret.insert(ret.end(), it->second.begin(), it->second.end());
                }
            }
            return ret;
        }
    };
  • 相关阅读:
    update语句中存在''语法书写方式
    CSS的代码风格
    CSS的语法规范
    CSS层叠样式表导读
    CSS简介
    HTML基本标签(下)
    HTML基本标签(上)
    HTML简介导读
    集合及其运用
    字典的镶嵌
  • 原文地址:https://www.cnblogs.com/tonix/p/3904497.html
Copyright © 2011-2022 走看看