LintCode Q171 Anagrams in Python

  • Jinhai ZHOU
  • 3 Minutes
  • 2016年12月16日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
# @param strs: A list of strings
# @return: A list of strings
def anagrams(self, strs):
hash_map = {}
res = []
# write your code here
# time complexity = O(m*n)
# input list length n, max entry string length m
# space complexity = O(n)
for str in strs:
occurence = [0]*26 #list
for c in str:
occurence[ord(c) - ord('a')] += 1
if repr(occurence) in hash_map:
hash_map[repr(occurence)].append(str)
else:
hash_map[repr(occurence)] = [str]
for key in hash_map:
if len(hash_map[key]) > 1:
res.extend(hash_map[key])
return res
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。