Last active
November 3, 2023 06:20
-
-
Save james4388/e28d4b28cda17022a150fd31ce20d5be to your computer and use it in GitHub Desktop.
StringTree Kotlin
This file contains 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.lang.IndexOutOfBoundsException | |
abstract class Node { | |
var length: Int = 0 | |
abstract fun charAt(index: Int): Char | |
abstract fun subString(start: Int, end: Int): String | |
abstract fun delete(index: Int) | |
} | |
class InternalNode(length: Int = 0, var left: Node? = null, var right: Node? = null) : Node() { | |
init { | |
this.length = length | |
} | |
override fun charAt(index: Int): Char { | |
if (index >= length) { | |
throw IndexOutOfBoundsException() | |
} | |
if (left != null && index < left!!.length) { | |
return left!!.charAt(index) | |
} | |
if (right != null) { | |
return right!!.charAt(index - left!!.length) | |
} | |
throw IndexOutOfBoundsException() | |
} | |
override fun subString(start: Int, end: Int): String { | |
val substr = StringBuilder() | |
if (left != null && start < left!!.length) { | |
substr.append(left!!.subString(start, minOf(end, left!!.length - 1))) | |
} | |
if (right != null && end >= left!!.length) { | |
substr.append(right!!.subString(0, end - left!!.length)) | |
} | |
return substr.toString() | |
} | |
override fun delete(index: Int) { | |
if (index >= length) { | |
throw IndexOutOfBoundsException() | |
} | |
if (left != null && index < left!!.length) { | |
left!!.delete(index) | |
} | |
if (right != null) { | |
right!!.delete(index - left!!.length) | |
} | |
} | |
} | |
class Leaf(var string: String = "", length: Int = 0) : Node() { | |
init { | |
if (length == 0) { | |
this.length = string.length | |
} else { | |
this.length = length | |
} | |
} | |
override fun charAt(index: Int): Char { | |
if (index >= length) { | |
throw IndexOutOfBoundsException() | |
} | |
return string[index] | |
} | |
override fun subString(start: Int, end: Int): String { | |
return string.substring(start, end + 1) | |
} | |
override fun delete(index: Int) { | |
if (index >= length) { | |
throw IndexOutOfBoundsException() | |
} | |
string = string.substring(0, index) + string.substring(index + 1) | |
length-- | |
} | |
} | |
class StringTree { | |
var root: InternalNode = InternalNode() | |
} | |
fun main() { | |
val leaf1 = Leaf(string = "ABCDE") | |
val leaf2 = Leaf(string = "FGHIJKLMNO") | |
val leaf3 = Leaf(string = "PQRSTUVWXYZ") | |
val inode1 = InternalNode(21, left = leaf2, right = leaf3) | |
val root = InternalNode(26, left = leaf1, right = inode1) | |
println(root.charAt(25)) | |
println(root.subString(1, 3)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment