Advertisement
Guest User

Untitled

a guest
Jan 1st, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.26 KB | None | 0 0
  1. sealed class Trie(val cs: HashMap<Char, Node>) {
  2.     class Root(cs: HashMap<Char, Node>): Trie(cs)
  3.     class Node(cs: HashMap<Char, Node>, var count: Int): Trie(cs)
  4.    
  5.     fun matches(s: String): Int {
  6.         return if (s.isEmpty()) {
  7.             when (this) {
  8.                 is Root -> error(":()")
  9.                 is Node -> this.count
  10.             }
  11.         } else {
  12.             this.cs[s.first()]?.matches(s.drop(1))?: 0
  13.         }
  14.     }
  15.    
  16.     fun insert(s: String, root: String = s): Trie {
  17.         return if (s.isEmpty()) {
  18.             this
  19.         } else {
  20.             val oldNode = this.cs[s.first()]?: Node(hashMapOf(), 0)
  21.             val newNode = oldNode.insert(s.drop(1), root) as Node
  22.            
  23.             newNode.count ++
  24.             this.cs.put(s.first(), newNode)
  25.            
  26.             this
  27.         }
  28.     }
  29.    
  30.     companion object {
  31.         fun empty(): Trie = Root(hashMapOf())
  32.     }
  33. }
  34.    
  35. fun main(args: Array<String>) {
  36.     val trie = Trie.empty()
  37.    
  38.     val numOps = readLine()!!.toInt()
  39.     for (i in (1 .. numOps)) {
  40.         val (op, value) = readLine()!!.split(" ")
  41.         if (op == "add") {
  42.             trie.insert(value)
  43.         } else {
  44.             println(trie.matches(value))
  45.         }
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement