String operation, which is the strong aspect of Python. Anagram means same characters but different sequences, hence we can resort the word and judge if it is the same.
Note sorted(string) will return a list of sorted sequence.
Solution:
# T:O(n) S:O(n) class Solution: # @param {string[]} strs # @return {string[]} def anagrams(self, strs): N = len(strs) if N == 0 or N == 1: return [] dict, result = {}, [] for word in strs: anag = ''.join(sorted(word)) if anag not in dict: dict[anag] = [word] else: dict[anag] += [word] for key in dict: if len(dict[key]) > 1: ret += dict[key] return retRun Time: 100 ms
No comments:
Post a Comment