-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathAnagrams.py
More file actions
36 lines (27 loc) · 815 Bytes
/
Anagrams.py
File metadata and controls
36 lines (27 loc) · 815 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
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"].
Note
All inputs will be in lower-case
"""
from collections import defaultdict
__author__ = 'Daniel'
class Solution(object):
def anagrams(self, strs):
ret = []
cnt = defaultdict(int)
for s in strs:
enc = self.encode(s)
cnt[enc] += 1
for s in strs:
enc = self.encode(s)
if cnt[enc] > 1:
ret.append(s)
return ret
def encode(self, s):
ret = [0 for _ in xrange(26)]
for c in s:
ret[ord(c)-ord('a')] += 1
return "".join(map(str, ret))