-
Notifications
You must be signed in to change notification settings - Fork 0
/
49 GROUP ANAGRAMS.rtf
55 lines (53 loc) · 1.87 KB
/
49 GROUP ANAGRAMS.rtf
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
{\rtf1\ansi\ansicpg1252\cocoartf2706
\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fnil\fcharset0 HelveticaNeue;}
{\colortbl;\red255\green255\blue255;}
{\*\expandedcolortbl;;}
\margl1440\margr1440\vieww11520\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0
\f0\fs24 \cf0 49. GROUP ANAGRAM \
\
\pard\pardeftab560\slleading20\partightenfactor0
\f1\fs26 \cf0 #GROUP ANAGRAM\
class Solution:\
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\
Hashmap = defaultdict(list)\
for words in strs:\
count = [0]*26\
for i in range(len(words)):\
count[ord(words[i])-ord('a')] += 1\
\
# two cases if the word already in hashmap or if the word not in hashmap \
\
if tuple(count) not in Hashmap:\
#append the new list\
Hashmap[tuple(count)] = [words]\
else:\
#update add the words in the list\
Hashmap[tuple(count)].append(words)\
\
#Hashmap[tuple(count)].append(words)\
\
\
return Hashmap.values()\
\pard\pardeftab560\slleading20\pardirnatural\partightenfactor0
\cf0 \
\pard\pardeftab560\slleading20\partightenfactor0
\cf0 # Neetcode approach \
\
dicti = defaultdict(list) # countofcharacterarray : [list of words that matches count]\
\
for s in strs:\
count = [0] * 26\
\
for c in s:\
\
#generate keys \
count[ord(c)-ord('a')] +=1\
\
#adding word to hashmap dicti\
#note: list cannot be keys so convert \
#note: what if key not present that is why we use default dict \
dicti[tuple(count)].append(s)\
\
return dicti.values()\
}