zoukankan      html  css  js  c++  java
  • leetcode刷题笔记 208题 实现Trie(前缀树)

    leetcode刷题笔记 208题 实现Trie(前缀树)

    源地址:208. 实现 Trie (前缀树)

    问题描述:

    实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

    示例:

    Trie trie = new Trie();

    trie.insert("apple");
    trie.search("apple"); // 返回 true
    trie.search("app"); // 返回 false
    trie.startsWith("app"); // 返回 true
    trie.insert("app");
    trie.search("app"); // 返回 true
    说明:

    你可以假设所有的输入都是由小写字母 a-z 构成的。
    保证所有输入均为非空字符串。

    class Trie() {
    
        /** Initialize your data structure here. */
        class Node(val children: Array[Node], var isWordEnd: Boolean)
        //每个节点包括对应26个字母的位置, 依次将单词拆成字符放入树的每一层
        val root = new Node(new Array[Node](26), false)
    	
        //逐个字母检查,若为空说明不存在,否则进入对应的下一层的节点
        def searchHelper(word: String): Node = {
            var ptr = root
            for (ch <- word){
                if (ptr.children(ch - 'a') == null) return null
                ptr = ptr.children(ch - 'a')
            }
            return ptr
        }
    
        /** Inserts a word into the trie. */
        //逐层插入,若下层没有节点进行新建
        def insert(word: String) {
            var ptr = root
            for (ch <- word){
                if (ptr.children(ch - 'a') == null) ptr.children(ch - 'a') = new Node(new Array[Node](26), false)
                ptr = ptr.children(ch - 'a')
            }
            //对于单词结尾进行标注
            ptr.isWordEnd = true
        }
    
        /** Returns if the word is in the trie. */
        def search(word: String): Boolean = {
            val ptr = searchHelper(word)
            if (ptr == null) false else ptr.isWordEnd
        }
    
        /** Returns if there is any word in the trie that starts with the given prefix. */
        def startsWith(prefix: String): Boolean = {
            searchHelper(prefix) != null
        }
    
    }
    
    /**
     * Your Trie object will be instantiated and called as such:
     * var obj = new Trie()
     * obj.insert(word)
     * var param_2 = obj.search(word)
     * var param_3 = obj.startsWith(prefix)
     */
    
  • 相关阅读:
    在xcode5中修改整个项目名
    如何调试堆损坏
    My Life with Isaac Stern by Aaron Rosand
    Seagate 硬盘产地查询
    服务器返回 HTTP 500
    Exception code: 0xE0434352
    When curl sends 100-continue
    Milestone 不能卸载,修复 Counter 即可
    GE 遇到的 UAC 导致不能自动启动的问题
    关于 UAC,Mark Russinovich on the Future of Security
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13733128.html
Copyright © 2011-2022 走看看