Commit ae94c8df authored by Ilya Prokhorov's avatar Ilya Prokhorov

Longest repeated substring by suffix array sorting

parent 6ffdf269
import kotlin.math.min
fun main(args: Array<String>) {
val searchString = "adasDATAHEADER??jpjjwerthhkjbcvkDATAHEADER??kkasdf"
searchLongestRepeatedSubstring(searchString)
}
fun longestPrefix(lhs: String, rhs: String): String {
val maximalLength = min(lhs.length-1, rhs.length -1)
for (i in 0..maximalLength) {
val xChar = lhs.take(i)
val yChar = rhs.take(i)
if (xChar != yChar) {
return lhs.substring(0, i-1)
}
}
return lhs.substring(0,maximalLength)
}
fun searchLongestRepeatedSubstring(searchString: String): String {
val suffixTree = suffixTree(searchString)
val sortedSuffixTree = suffixTree.sorted()
var longestRepeatedSubstring = ""
for (i in 0..sortedSuffixTree.count() - 2) {
val lhs = sortedSuffixTree[i]
val rhs = sortedSuffixTree[i+1]
val longestPrefix = longestPrefix(lhs, rhs)
if (longestRepeatedSubstring.length < longestPrefix.length) {
longestRepeatedSubstring = longestPrefix
}
}
return longestRepeatedSubstring
}
fun suffixTree(string: String): Array<String> {
var suffixTree = ArrayList<String>()
for (i in 0..string.length - 1) {
val substring = string.substring(i)
suffixTree.add(substring)
}
return suffixTree.toTypedArray()
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="KotlinJavaRuntime" level="project" />
</component>
</module>
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment