• 208. Implement Trie (Prefix Tree)


    Implement a trie with insertsearch, and startsWith methods.

    题目含义:实现字典树的insertsearch, 和startsWith 方法

    字典树概念参考http://blog.csdn.net/u012501459/article/details/46741267

    Trie树的基本性质如下:

    • 根节点不包括字符,除根节点外每个节点包括一个字符。
    • 从根节点到某一节点,路径上经过的字符连接起来,即为对应的字符串。
    • 每个节点的所有子节点包含的字符串各不相同。

    本题中的Trie树可以简单实现如下:

    Trie树节点数据结构定义如下:

    1. val表示该节点对应的字符
    2. 子节点简单用一个数组表示,这样实现比较简单,但比较耗费内存
    3. isWord标记从根节点到该节点是否表示一个单词,还是另一单词的前缀。
     1 class Trie {
     2     
     3     class TrieNode {
     4         public char val;
     5         public boolean isWord;
     6         public TrieNode[] children = new TrieNode[26];
     7         public TrieNode() {}
     8         TrieNode(char c){
     9             val = c;
    10         }
    11     }
    12     
    13     private TrieNode root;
    14     /** Initialize your data structure here. */
    15     public Trie() {
    16         root = new TrieNode();
    17         root.val = ' ';        
    18     }
    19     
    20     /** Inserts a word into the trie. */
    21     public void insert(String word) {
    22         TrieNode ws = root;
    23         for(int i = 0; i < word.length(); i++){
    24             char c = word.charAt(i);
    25             if(ws.children[c - 'a'] == null){
    26                 ws.children[c - 'a'] = new TrieNode(c);
    27             }
    28             ws = ws.children[c - 'a'];
    29         }
    30         ws.isWord = true;        
    31     }
    32     
    33     /** Returns if the word is in the trie. */
    34     public boolean search(String word) {
    35         TrieNode ws = root;
    36         for(int i = 0; i < word.length(); i++){
    37             char c = word.charAt(i);
    38             if(ws.children[c - 'a'] == null) return false;
    39             ws = ws.children[c - 'a'];
    40         }
    41         return ws.isWord;        
    42     }
    43     
    44     /** Returns if there is any word in the trie that starts with the given prefix. */
    45     public boolean startsWith(String prefix) {
    46         TrieNode ws = root;
    47         for(int i = 0; i < prefix.length(); i++){
    48             char c = prefix.charAt(i);
    49             if(ws.children[c - 'a'] == null) return false;
    50             ws = ws.children[c - 'a'];
    51         }
    52         return true;        
    53     }
    54 }
  • 相关阅读:
    HDU1698(线段树入门题)
    POJ2528(离散化+线段树区间更新)
    POJ3630(Trie树)
    HDU1251(字典树)
    HDU1247(经典字典树)
    POJ2513(字典树+图的连通性判断)
    POJ1363
    UVa11624(逃离火焰问题)
    HDOJ1495(倒水BFS)
    poj3414Pots(倒水BFS)
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7725618.html
Copyright © 2020-2023  润新知