-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0890-find-and-replace-pattern.py
More file actions
47 lines (41 loc) · 1.33 KB
/
0890-find-and-replace-pattern.py
File metadata and controls
47 lines (41 loc) · 1.33 KB
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
# time complexity: O(n^2)
# space complexity: O(n)
from collections import defaultdict
from typing import List
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
result = []
for word in words:
if len(word) != len(pattern):
break
patternDict = defaultdict(str)
wordDict = defaultdict(str)
match = True
for i in range(len(pattern)):
patternC = pattern[i]
wordC = word[i]
if patternC not in patternDict:
patternDict[patternC] = wordC
if patternC in patternDict and wordC != patternDict[patternC]:
match = False
break
if wordC not in wordDict:
wordDict[wordC] = patternC
if wordC in wordDict and patternC != wordDict[wordC]:
match = False
break
if match:
result.append(word)
return result
'''
a:c
b:c
b:c
in patternC and wordC != patternDict[]
'''
words = ["abc", "deq", "mee", "aqq", "dkd", "ccc"]
pattern = "abb"
print(Solution().findAndReplacePattern(words, pattern))
words = ["a", "b", "c"]
pattern = "a"
print(Solution().findAndReplacePattern(words, pattern))