Created
July 23, 2018 18:40
-
-
Save ekeitho/9620b5d181da7b714b6b728bd0f9206c to your computer and use it in GitHub Desktop.
PreFixMapSum
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
package cracking.ch4 | |
import org.junit.Test | |
import java.util.* | |
class PrefixMapSum { | |
var trie = Trie(0) | |
@Test | |
fun test() { | |
val pre = PrefixMapSum() | |
pre.insert("columnar", 3) | |
println(pre.sum("col")) | |
pre.insert("column", 2) | |
println(pre.sum("col")) | |
println(pre.sum("columnar")) | |
} | |
fun insert(key: String, value: Int) { | |
var tempTrie = trie | |
for (letter in 0 until key.length) { | |
val index = key[letter] - 'a' | |
if (tempTrie.children[index] == null) { | |
tempTrie.children[index] = Trie(value) | |
} else { | |
tempTrie.children[index]!!.sum += value | |
} | |
tempTrie = tempTrie.children[index]!! | |
} | |
} | |
tailrec fun recur(tempTrie: Trie?, prefix: String) : Int { | |
if (tempTrie == null || prefix.isEmpty()) return 0 | |
if (prefix.length == 1) { | |
return tempTrie.sum | |
} | |
return recur(tempTrie.children[prefix[0] - 'a'], prefix.substring(1, prefix.length)) | |
} | |
fun sum(prefix: String) : Int { | |
val tempTrie = trie; | |
return recur(tempTrie, prefix) | |
} | |
} | |
data class Trie(var sum: Int, var children: Array<Trie?> = arrayOfNulls(26)) { | |
override fun equals(other: Any?): Boolean { | |
if (this === other) return true | |
if (javaClass != other?.javaClass) return false | |
other as Trie | |
if (sum != other.sum) return false | |
if (!Arrays.equals(children, other.children)) return false | |
return true | |
} | |
override fun hashCode(): Int { | |
var result = sum | |
result = 31 * result + Arrays.hashCode(children) | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
tailrec - will rewrite recursion method in an while loop. The improvements come from the fact that method calls are more expensive than simply looping and reduces risk of stack overflow.
Decompiled Java: