- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstring_replace.py
More file actions
Latest commit
69 lines (55 loc) · 2.19 KB
/
Copy pathstring_replace.py
File metadata and controls
69 lines (55 loc) · 2.19 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
importunittest
fromtypingimportList
classTireNode:
def__init__(self):
self.children= {}
# replacement表示从根节点到当前节点组成的字符串(在数组A中),能替换成数组B的哪个字符串
self.replacement=None
classTire:
def__init__(self):
self.root=TireNode()
definsert(self, word: str, replacement: str):
curr=self.root
forcharinword:
# Insert key with a value of default if key is not in the dictionary.
# Return the value for key if key is in the dictionary, else default.
curr=curr.children.setdefault(char, TireNode())
curr.replacement=replacement
defsearch(self, word: str) ->str:
curr, replacement=self.root, None
forcharinword:
ifcharnotincurr.children:
break
curr=curr.children[char]
# 不断搜索字典树,找到新的(更长的replacement)就更新
ifcurr.replacementisnotNone:
replacement=curr.replacement
# 如果没找到,就返回第一个字符,让字符串S原封不动地替换下一个字符,然后指针会后移一位
ifreplacementisNone:
replacement=word[0]
returnreplacement
classSolution(unittest.TestCase):
TEST_CASES= [
# ababa -> cccba -> cccba
# ^ ^ ^
(["ab", "aba"], ["cc", "ccc"], "ababa", "cccba"),
]
deftest(self):
fora, b, s, after_replaceinself.TEST_CASES:
self.assertEqual(after_replace, self.f(a, b, s))
@staticmethod
deff(a: List[str], b: List[str], s: str) ->str:
ifnotaornotb:
returns
tire=Tire()
fori, wordinenumerate(a):
# 只有word是s的子串其才会被放到trie中, 这样就保证了每次search的时候, 每次匹配s[i]做的都是有用功
ifwordins:
tire.insert(word, b[i])
result=""
whiles:
replacement=tire.search(s)
print(replacement)
result+=replacement
s=s[len(replacement):]
returnresult