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

    Implement a trie with insert, search, and startsWith methods.

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

    Solution:

     1 class TrieNode {
     2     TrieNode[] childs;
     3     boolean hasWords;
     4     
     5     // Initialize your data structure here.
     6     public TrieNode() {
     7         childs = new TrieNode[26];
     8         hasWords = false;
     9     }
    10 }
    11 
    12 public class Trie {
    13     private TrieNode root;
    14 
    15     public Trie() {
    16         root = new TrieNode();
    17     }
    18 
    19     // Inserts a word into the trie.
    20     public void insert(String word) {
    21         TrieNode cur = root;
    22         for (int i=0;i<word.length();i++){
    23             char curChar = word.charAt(i);
    24             if (cur.childs[curChar-'a']==null){
    25                 cur.childs[curChar-'a'] = new TrieNode();
    26             } 
    27             cur = cur.childs[curChar-'a'];
    28         }
    29         cur.hasWords = true;
    30     }
    31 
    32     // Returns if the word is in the trie.
    33     public boolean search(String word) {
    34         TrieNode cur = root;
    35         for (int i=0;i<word.length();i++){
    36             char curChar = word.charAt(i);
    37             if (cur.childs[curChar-'a']==null){
    38                 return false;
    39             }
    40             cur = cur.childs[curChar-'a'];
    41         }
    42         return cur.hasWords;
    43     }
    44 
    45     // Returns if there is any word in the trie
    46     // that starts with the given prefix.
    47     public boolean startsWith(String prefix) {
    48         TrieNode cur = root;
    49         for (int i=0;i<prefix.length();i++){
    50             char curChar = prefix.charAt(i);
    51             if (cur.childs[curChar-'a']==null){
    52                 return false;
    53             }
    54             cur = cur.childs[curChar-'a'];
    55         }
    56         return true;
    57     }
    58 }
    59 
    60 // Your Trie object will be instantiated and called as such:
    61 // Trie trie = new Trie();
    62 // trie.insert("somestring");
    63 // trie.search("key");
  • 相关阅读:
    URAL-1998 The old Padawan 二分
    URAL-1997 Those are not the droids you're looking for 二分匹配
    URAL-1991 The battle near the swamp 水题
    URAL-1989 Subpalindromes 多项式Hash+树状数组
    URAL-1987 Nested Segments 线段树简单区间覆盖
    URAL-1981 Parallel and Perpendicular 水题
    k8s-api
    golang test模块
    k8s-calico
    docker设置proxy
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5794310.html
Copyright © 2011-2022 走看看