Skip to content

Commit e3d6198

Browse files
committed
Create 833.find-and-replace-in-string.py
1 parent ad825c2 commit e3d6198

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

833.find-and-replace-in-string.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# https://leetcode.cn/problems/find-and-replace-in-string
2+
3+
4+
class Solution1:
5+
'''
6+
Date: 2023.08.15
7+
Pass/Error/Bug: 2/1/0
8+
执行用时: 44 ms, 在所有 Python3 提交中击败了 69.51% 的用户
9+
内存消耗:15.69 Mb, 在所有 Python3 提交中击败了 78.05% 的用户
10+
'''
11+
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
12+
new_s = ''
13+
14+
hash_dict = {}
15+
16+
for idx in range(len(indices)):
17+
hash_dict[indices[idx]] = [ sources[idx], targets[idx] ]
18+
19+
for idx in sorted(hash_dict.keys()):
20+
new_s = s[:idx]
21+
break
22+
23+
gap_idx = idx
24+
for idx in sorted(hash_dict.keys()):
25+
sub_s, s_target = hash_dict[idx]
26+
sub_l = len(sub_s)
27+
28+
if gap_idx != idx:
29+
new_s += s[gap_idx:idx]
30+
gap_idx = idx
31+
32+
if s[idx:idx+sub_l] == sub_s:
33+
new_s += s_target
34+
else:
35+
new_s += s[idx:idx+sub_l]
36+
37+
gap_idx = idx+sub_l
38+
39+
40+
if gap_idx < len(s):
41+
new_s += s[gap_idx:]
42+
43+
return new_s

0 commit comments

Comments
 (0)