Anagrams

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

Example

Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"].

Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].

Solution

找到所有的符合长度相同顺序不同的词组。

所谓 anagram, 就是两个词所用的字母及其个数都是一样的,但是,字母的位置不一样。比如 abcc 和 cbca 就是 anagram. 判断的方法比较简单,先把单个字母(字符)转成整数,然后利用了hashtable+计数器的原理进行判断。

class Solution:
    # @param strs: A list of strings
    # @return: A list of strings
    def anagrams(self, strs):
        # write your code here
        dict = {}
        for word in strs:
            sortedword = ''.join(sorted(word))
            dict[sortedword] = [word] if sortedword not in dict else dict[sortedword] + [word]
        res = []
        for item in dict:
            if len(dict[item]) >= 2:
                res += dict[item]
        return res

Last updated

Was this helpful?