Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sealed class Trie(val cs: HashMap<Char, Node>) {
- class Root(cs: HashMap<Char, Node>): Trie(cs)
- class Node(cs: HashMap<Char, Node>, var count: Int): Trie(cs)
- fun matches(s: String): Int {
- return if (s.isEmpty()) {
- when (this) {
- is Root -> error(":()")
- is Node -> this.count
- }
- } else {
- this.cs[s.first()]?.matches(s.drop(1))?: 0
- }
- }
- fun insert(s: String, root: String = s): Trie {
- return if (s.isEmpty()) {
- this
- } else {
- val oldNode = this.cs[s.first()]?: Node(hashMapOf(), 0)
- val newNode = oldNode.insert(s.drop(1), root) as Node
- newNode.count ++
- this.cs.put(s.first(), newNode)
- this
- }
- }
- companion object {
- fun empty(): Trie = Root(hashMapOf())
- }
- }
- fun main(args: Array<String>) {
- val trie = Trie.empty()
- val numOps = readLine()!!.toInt()
- for (i in (1 .. numOps)) {
- val (op, value) = readLine()!!.split(" ")
- if (op == "add") {
- trie.insert(value)
- } else {
- println(trie.matches(value))
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement