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
|
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.util.*
val br = BufferedReader(InputStreamReader(System.`in`))
val bw = BufferedWriter(OutputStreamWriter(System.out))
fun main()=with(br){
val parent = "ababacabacaabacaaba"
val pattern = "abacaaba"
KMP(parent, pattern)
bw.flush()
bw.close()
}
fun makeTable(pattern:String):IntArray{
val patternSize = pattern.length
val table = IntArray(patternSize){0}
var j = 0
for(i in 1 until patternSize){
while(j>0 && pattern[i]!=pattern[j]){
j=table[j-1]
}
if(pattern[i]==pattern[j]){
table[i]=++j
}
}
return table
}
fun KMP(parent:String, pattern:String){
val table = makeTable(pattern)
val parentSize = parent.length
val patternSize = pattern.length
var j = 0
for(i in 0 until parentSize){
while(j>0 && parent[i]!=pattern[j]){
j=table[j-1]
}
if(parent[i]==pattern[j]){
if(j==patternSize-1){
println("${i-patternSize+2}에서 찾았습니다.")
j=table[j]
}
else{
j++
}
}
}
}
|
cs |
'알고리즘 공부 > KMP 알고리즘' 카테고리의 다른 글
백준 1786번 with Kotlin (0) | 2021.08.14 |
---|---|
5525번 with Kotlin (0) | 2021.08.14 |