Problem
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Code
vector<string> anagrams(vector<string> &strs) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<string> result; map<string,vector<string> > angmap; vector<string>::const_iterator it = strs.begin(); for(;it != strs.end(); ++it){ string tmp = *it; sort(tmp.begin(),tmp.end()); angmap[tmp].push_back(*it); } map<string,vector<string> >::const_iterator mit = angmap.begin(); for(; mit != angmap.end(); ++mit){ vector<string> temp = mit->second; if(temp.size() > 1) copy(temp.begin(),temp.end(),back_inserter<vector<string> >(result)); } return result; }
No comments:
Post a Comment