Median of Two Sorted Arrays @ LeetCode (Python)
Jump Game @ LeetCode (Python)

Anagrams @ LeetCode (Python)

kitt posted @ 2014年2月17日 18:50 in LeetCode , 2860 阅读

key = sorted word, value = [word1, word2, word3, ...]

class Solution:
    # @param strs, a list of strings
    # @return a list of strings
    def anagrams(self, strs):
        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
Avatar_small
xyz 说:
2014年3月18日 00:01

Hello, I tried your code but changed it a little bit: instead of dict[sortedWord]+[word] I tried dict[sortedWord].append(word) and it erases all the elements in dict[sortedWord]...I feel so confused...

Avatar_small
kitt 说:
2014年3月18日 01:42

@xyz: Hi, I've made the same mistake before. The differences are that the return value of .append() is None and the return value of list1 + list2 is a list.

>>> A = ['abc']
>>> A.append('def')
>>> A
['abc', 'def']
>>> A + ['def']
['abc', 'def', 'def']
>>>

The meaning of "dict[sortedWord] = [word] if sortedWord not in dict else dict[sortedWord] + [word]" is this:
if sortedWord not in dict:
dict[sortedWord] = [word]
else:
dict[sortedWord] = dict[sortedWord] + [word]

If you want to use append(), it should be:
if sortedWord not in dict:
dict[sortedWord] = [word]
else:
dict[sortedWord].append(word)

Now you see the problem of "dict[sortedWord] = [word] if sortedWord not in dict else dict[sortedWord].append(word)" ?

Avatar_small
xyz 说:
2014年3月18日 12:31

Thanks a lot for your explanation! It is clear to me now :)

Avatar_small
kitt 说:
2014年3月18日 17:42

@xyz:
You are welcome :)

Avatar_small
FooBee 说:
2014年5月23日 14:02
class Solution:
    # @param strs, a list of strings
    # @return a list of strings
    def anagrams(self, strs):
        D=collections.defaultdict(list)
        for s in strs:
            D[''.join(sorted(s))].append(s)
        res = []
        for los in D.values():
            if(len(los)>=2):
                res.extend(los)
        return res
 
这里用defaultdict更简洁一些吧

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter