Friday, May 2, 2014

LeetCode: Anagrams

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.


According to wikipedia, An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once. So we can use a hashmap to store the set of anagrams with the key as letters alphabetical ordered.

C++ Code:

/*
 * func: get_key
 * goal: reordering the word in lexical order
 * @param word: input string
 * return: reordered word
 */
string get_key(const string& word){
    vector<int> letter_map(26, 0);
    for(const char &letter : word){
        letter_map[letter-'a'] += 1;
    }
    string result = "";
    for(int i=0; i<26; ++i){
        for(int j=0; j < letter_map[i];++j){
            result += i + 'a';
        }
    }
    return result;
}
/*
 * func: group_anagram
 * goal: group strings that are anagrams
 * @param strs: an array of strings
 * return: vector of anagrams
 */
/*
 * use a hashmap to help identify anagrams
 * complexity: time O(n), space O(n)
 */
vector<string> anagrams(vector<string> &strs){
    vector<string> result;
    unordered_map<string, vector<string> > dict;
    for(const string &word : strs){
        string key = get_key(word);
        dict[key].emplace_back(word);
    }
    for(auto it = dict.begin(); it != dict.end(); ++it){
        if((it->second).size() > 1){
            for(const string &word : it->second){
                result.emplace_back(word);
            }
        }
    }
    
    return result;
}

Python Code:

# func: return all groups of strings that are anagrams
# @param strs: input word list
# @return: a list of words which are anagrams
def anagrams(strs):
    word_dict = {}
    for word in strs:
        convert_word = list(word)
        convert_word.sort()
        convert_word = ''.join(x for x in convert_word)
        if convert_word in word_dict:
            word_dict[convert_word].append(word)
        else:
            word_dict[convert_word] = [word]

    result = []
    for word in word_dict:
        if len(word_dict[word]) > 1:
            result += [anagram for anagram in word_dict[word]]

    return result

No comments:

Post a Comment