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

    Description:

    Implement a trie with insertsearch, and startsWith methods.

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

    实现一个简单的Trie树,参考我的博客:http://www.cnblogs.com/wxisme/p/4876197.html

     1 class TrieNode {
     2     public TrieNode[] son;
     3     public boolean isEnd;
     4     // Initialize your data structure here.
     5     public TrieNode() {
     6         this.son = new TrieNode[26];
     7         isEnd = false;
     8         
     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         char[] wordChars = word.toCharArray();
    22         TrieNode node = this.root;
    23         for(char ch : wordChars) {
    24             int pos = ch - 'a';
    25             if(node.son[pos] == null) {
    26                 node.son[pos] = new TrieNode();
    27             }
    28             node = node.son[pos];
    29         }
    30         node.isEnd = true;
    31     }
    32 
    33     // Returns if the word is in the trie.
    34     public boolean search(String word) {
    35         char[] wordChars = word.toCharArray();
    36         TrieNode node = this.root;
    37         for(char ch : wordChars) {
    38             int pos = ch - 'a';
    39             if(node.son[pos] == null) {
    40                 return false;
    41             }
    42             node = node.son[pos];
    43         }
    44         return node.isEnd;
    45     }
    46 
    47     // Returns if there is any word in the trie
    48     // that starts with the given prefix.
    49     public boolean startsWith(String prefix) {
    50         
    51         char[] prefixChars = prefix.toCharArray();
    52         TrieNode node = this.root;
    53         for(char ch : prefixChars) {
    54             int pos = ch - 'a';
    55             if(node.son[pos] == null) {
    56                 return false;
    57             }
    58             node = node.son[pos];
    59         }
    60         return true;
    61     }
    62 }
    63 
    64 // Your Trie object will be instantiated and called as such:
    65 // Trie trie = new Trie();
    66 // trie.insert("somestring");
    67 // trie.search("key");
  • 相关阅读:
    find命令进阶(二):对找到的文件执行操作exec
    find命令进阶用法(一)
    find按照文件大小查找
    find命令查找目录
    什么是ppa
    Linux进程管理命令
    [HDOJ4135]Co-prime
    [HDOJ5391]Zball in Tina Town
    [模拟]位运算实现四则运算
    [HDOJ1233]还是畅通工程
  • 原文地址:https://www.cnblogs.com/wxisme/p/4876980.html
Copyright © 2011-2022 走看看