typescrpit实现字典树(Trie)

自己随便写的,看看就好

class BookTree {
  public keys: Map<String, BookTree>
  public has: boolean

  constructor() {
    this.keys = new Map<String, BookTree>()
    this.has = false
  }

  public add(str: string): BookTree {
    let node: BookTree = this
    let next: BookTree
    let c: string
    let i = 0
    while (i < str.length) {
      c = str[i++]
      if (!node.keys.has(c)) {
        next = new BookTree()
        node.keys.set(c, next)
      } else next = <BookTree>node.keys.get(c)

      node = next
    }
    node.has = true
    return this
  }

  public include(str: string): boolean {
    let node: BookTree = this
    let c: string
    let i = 0
    while (i < str.length) {
      c = str[i++]
      if (!node.keys.has(c))
        return false
      node = <BookTree>node.keys.get(c)
    }
    return node.has
  }

  public startWith(str: string): boolean {
    let node: BookTree = this
    let c: string
    let i = 0
    while (i < str.length) {
      c = str[i++]
      if (!node.keys.has(c))
        return false
      node = <BookTree>node.keys.get(c)
    }
    return true
  }
}

/* 测试样例
~function test() {
  let root = new BookTree()
  root.add('abadcaw')
  root.add('abeeec')

  console.log(root.include('abeeec'))
  console.log(root.startWith('abee'))
}()
 */
posted @ 2022-07-18 22:21  ぃ往事深处少年蓝べ  阅读(32)  评论(0编辑  收藏  举报