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
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...
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)" ?
2014年3月18日 12:31
Thanks a lot for your explanation! It is clear to me now :)
2014年3月18日 17:42
@xyz:
You are welcome :)
2014年5月23日 14:02