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; } };