zoukankan      html  css  js  c++  java
  • Implement Trie (Prefix Tree) ——LeetCode

    Implement a trie with insertsearch, and startsWith methods.

    Note:
    You may assume that all inputs are consist of lowercase letters a-z.

    实现一个字典树。

    好久不做题,没感觉啊,TreeNode用一个布尔变量表示是否是一个合法单词的结尾即可,一开始还用cnt来计数,search的时候比较麻烦。

    class TrieNode {
        // Initialize your data structure here.
         TrieNode [] next;
        boolean valid;
        public TrieNode() {
            next = new TrieNode[26];
            valid=false;
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode ptr = root;
            for(char c:word.toCharArray()){
                if(ptr.next[c-'a']==null){
                    ptr.next[c-'a'] = new TrieNode();
                }
                ptr=ptr.next[c-'a'];
            }
            ptr.valid=true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            int last = 0;
            TrieNode ptr = root;
            for(char c:word.toCharArray()){
                if(ptr==null||ptr.next[c-'a']==null){
                    return false;
                }
                ptr=ptr.next[c-'a'];
            }
            return ptr.valid;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode ptr = root;
            for(char c:prefix.toCharArray()){
                if(ptr==null||ptr.next[c-'a']==null){
                    return false;
                }
                ptr=ptr.next[c-'a'];
            }
            return true;
        }
    }
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie = new Trie();
    // trie.insert("somestring");
    // trie.search("key");
  • 相关阅读:
    leetcode-654-最大二叉树
    leetcode-46-全排列
    图片懒加载?
    HTTP常见的状态码?
    线程与进程的区别?
    网页从输入网址到渲染完成经历了哪些过程?
    网页前端性能优化的方式有哪些?
    常见的浏览器内核有哪些?
    汇编语言--cpu的工作原理(寄存器)--手稿
    对于 vue3.0 特性你有什么了解的吗?
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4680853.html
Copyright © 2011-2022 走看看