Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2014-08-11 12:56  Tonix  阅读(157)  评论(0编辑  收藏  举报