-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboj_01786.swift
52 lines (43 loc) · 1.11 KB
/
boj_01786.swift
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
// 2022.03.31
// Dongyoung Kwon @Chuncheonian ([email protected])
// https://www.acmicpc.net/problem/1786
import Foundation
func kmpSearch(str: String, pattern: String) -> [Int] {
let s = Array(str)
let p = Array(pattern)
var result = [Int]()
let failFunc = getFailFunc(pattern: p)
var j = 0
for i in 0..<s.count {
while j > 0, s[i] != p[j] {
j = failFunc[j - 1]
}
if s[i] == p[j] {
if j == p.count - 1 {
result.append(i - p.count + 2)
j = failFunc[j]
} else {
j += 1
}
}
}
return result
}
func getFailFunc(pattern p: [Character]) -> [Int] {
var failFunc = [Int](repeating: 0, count: p.count)
var j = 0
for i in 1..<p.count {
while j > 0, p[i] != p[j] {
j = failFunc[j-1]
}
if p[j] == p[i] {
j += 1
}
failFunc[i] = j
}
return failFunc
}
let (t, p) = (readLine()!, readLine()!)
let answer = kmpSearch(str: t, pattern: p)
print(answer.count)
answer.forEach{ print($0) }