-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathtask.go
64 lines (53 loc) · 1.03 KB
/
task.go
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
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func main() {
s := strings.Builder{}
Solution(os.Stdin, &s)
fmt.Println(s.String())
}
func Solution(r io.Reader, w *strings.Builder) {
scanner := bufio.NewScanner(r)
const bufCapacity = 10000000 // fix long string
buf := make([]byte, bufCapacity)
scanner.Buffer(buf, bufCapacity)
var text, s, t string
scanner.Scan()
text = scanner.Text()
scanner.Scan()
s = scanner.Text()
scanner.Scan()
t = scanner.Text()
sentinel := s + "#" + text
patternLen := len(s)
prefixLen := patternLen + 1
dp := make([]int, len(sentinel))
result := make([]bool, len(text))
for i := prefixLen; i < len(sentinel); i++ {
k := dp[i-1]
for sentinel[i] != sentinel[k] && k > 0 {
k = dp[k-1]
}
if sentinel[k] != sentinel[i] {
dp[i] = k
} else {
dp[i] = k + 1
if dp[i] == patternLen {
result[i-patternLen*2] = true
}
}
}
for i := 0; i < len(text); i++ {
if result[i] {
w.WriteString(t)
i += patternLen - 1
} else {
w.WriteByte(text[i])
}
}
}