-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathh.py
More file actions
84 lines (55 loc) · 1.64 KB
/
Copy pathh.py
File metadata and controls
84 lines (55 loc) · 1.64 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from __future__ import annotations
import sys
from collections.abc import Iterable, Sequence
def replace(s: str, pattern: str, replacement: str) -> Iterable[str]:
s_length = len(s)
pattern_length = len(pattern)
if s_length == 0 or pattern_length == 0 or s_length < pattern_length:
yield s
return
pi_array = _calculate_prefix_func_array(pattern)
i = j = s_pos = 0
while i < s_length:
if s[i] != pattern[j]:
if j == 0:
i += 1
else:
j = pi_array[j - 1]
continue
i += 1
j += 1
if j < pattern_length:
continue
s_part = s[s_pos:i - pattern_length]
if s_part:
yield s_part
if replacement:
yield replacement
s_pos = i
j = 0
s_part = s[s_pos:]
if s_part:
yield s_part
def _calculate_prefix_func_array(s: str) -> Sequence[int]:
s_length = len(s)
pi_array = [0] * s_length
pi_value = 0
for i in range(1, s_length):
current_char = s[i]
while True:
previous_char = s[pi_value]
chars_match = current_char == previous_char
if chars_match or pi_value == 0:
break
pi_value = pi_array[pi_value - 1]
if chars_match:
pi_value += 1
pi_array[i] = pi_value
return pi_array
def main() -> None:
s = sys.stdin.readline().strip()
pattern = sys.stdin.readline().strip()
replacement = sys.stdin.readline().strip()
print(*replace(s, pattern, replacement), sep='')
if __name__ == '__main__':
main()