Last active
July 8, 2020 14:41
-
-
Save richard1122/2ecf5b5c9d1bedaa50c9e937305d8fdf to your computer and use it in GitHub Desktop.
String construction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File | |
import java.io.FileInputStream | |
import java.util.* | |
// Unique index for each Vertex | |
var currentIndex = 0 | |
class Vertex(private val index: Int = ++currentIndex) { | |
var terminate = false | |
val edges = mutableMapOf<Char, Vertex>() | |
override fun equals(other: Any?): Boolean = other is Vertex && other.index == index | |
override fun hashCode(): Int = index | |
} | |
fun appendVertex(root: Vertex, template: String) { | |
var current: Vertex = root | |
template.forEach { char -> | |
val next = current.edges[char] | |
if (next == null) { | |
current.edges[char] = Vertex() | |
} | |
current = current.edges[char]!! | |
} | |
current.terminate = true | |
} | |
fun match(input: String, root: Vertex): Boolean { | |
val finalStates = input.fold(setOf(root), { states, char -> | |
val translationStates = mutableSetOf<Vertex>() // Next state set | |
states.forEach { | |
val nextState = it.edges[char] | |
if (nextState != null) { | |
// Can move to next state | |
translationStates.add(nextState) | |
// If current state is a terminate state (end of a template string), | |
// add root state. | |
// But current state is still available for next transition | |
if (nextState.terminate) translationStates.add(root) | |
} | |
// Else skip current state | |
} | |
translationStates | |
}) | |
return finalStates.any { it.terminate } | |
} | |
fun main(args: Array<String>) { | |
val scanner = Scanner(FileInputStream(File(args[0]))) | |
val input = scanner.nextLine() | |
val root = Vertex() | |
root.terminate = true | |
scanner.nextLine().split(' ').forEach { appendVertex(root, it) } | |
println(match(input, root)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
input
output
true