Thursday, April 19, 2012

Anagram Strings

[Question]:
Given a dictionary of words, find groups of anagram words.

[Analysis]:
Anagram words are words that share the same group of letters. Hash on the group of (sorted) letters to find anagram words in a dictionary.

[Solution]:

public static List<List<String>> getAnagrams(String[] dict)
{
Map<String, List<String>> hash = new HashMap();

for (String s: dict)
{
ArrayList<String> arrlist = new ArrayList<String>();
char[] chars = s.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);

if (!hash.containsKey(sorted)) {
hash.put(sorted, new ArrayList<String>());
}
hash.get(sorted).add(s);
}

List<List<String>> ret = new ArrayList<List<String>>();

for(List<String> list: hash.values()) {
if (list.size()>1) ret.add(list);
}

return ret;
}

//--- A C++ code, which is shorter. ---

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        unordered_map<string, vector<string>> map;
     
        for (auto s: strs) {
            string sorted = s;
            sort(sorted.begin(), sorted.end());
            map[sorted].push_back(s);
        }      
     
        vector<string> rslt;
        for (auto pair: map){
            if (pair.second.size()>1)
            rslt.insert(rslt.end(), pair.second.begin(), pair.second.end());
        }
        return rslt;
    }
};

No comments:

Post a Comment