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

    Implement a trie with insertsearch, and startsWith methods.

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

    由于用的是 26位字母的array, 所以在trieNode 上甚至不用存val。

     1 class TrieNode {
     2     // Initialize your data structure here.
     3     Boolean isWord;
     4     TrieNode[] children;
     5     
     6     public TrieNode(){
     7         this.isWord = false;
     8         children = new TrieNode[26];
     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             Character c = word.charAt(i);
    24             if(cur.children[c - 'a'] == null){
    25                 TrieNode tmp = new TrieNode();
    26                 cur.children[c - 'a'] = tmp;
    27             }
    28             cur = cur.children[c - 'a'];
    29         }
    30         cur.isWord = true;
    31     }
    32     
    33     private TrieNode findNode(String word){
    34         TrieNode cur = root;
    35         for(int i = 0; i < word.length(); i ++){
    36             Character c = word.charAt(i);
    37             if(cur.children[c - 'a'] == null){
    38                 return null;
    39             }
    40             cur = cur.children[c - 'a'];
    41         }
    42         return cur;
    43     }
    44     
    45     // Returns if the word is in the trie.
    46     public boolean search(String word) {
    47         TrieNode end = findNode(word);
    48         return end != null && end.isWord;
    49     }
    50 
    51     // Returns if there is any word in the trie
    52     // that starts with the given prefix.
    53     public boolean startsWith(String prefix) {
    54         return findNode(prefix) != null;
    55     }
    56 }
    57 
    58 // Your Trie object will be instantiated and called as such:
    59 // Trie trie = new Trie();
    60 // trie.insert("somestring");
    61 // trie.search("key");
  • 相关阅读:
    区间dp体会
    P1083借教室 noip提高组复赛2012
    P2678跳石头体会 noip2015提高组
    tarjan求LCA的体会
    P1006 传纸条
    P1140 相似基因 详解
    UVA1025 城市里的间谍 A Spy in the Metro 题解
    DAG上的动规嵌套矩形问题(含思考题)
    洛谷P1030c++递归求解先序排列
    Test 2019.7.22
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4487365.html
Copyright © 2011-2022 走看看