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

    /*
     * 208. Implement Trie (Prefix Tree) 
     * 2016-6-9 by Mingyang
     * 我在这里的时候用的hashmap来做的地图,这里用的是array,一样的原理
     * 不过我没有想到的是需要一个isEnd的property,因为这里的search必须找到end的时候才是成功的找到
     */
    class Tries {
        public TrieNode root;
        public Tries() {
            root = new TrieNode();
            root.isEnd = true;
        }
        public void insert(String word) {
            if (word == null || word.length() == 0)
                return;
            TrieNode node = root;
            char[] letters = word.toCharArray();
            for (int i = 0; i < word.length(); i++) {
                int pos = letters[i] - 'a';
                if (node.son[pos] == null) {
                    node.son[pos] = new TrieNode();
                    node.son[pos].val = letters[i];
                }
                node = node.son[pos];
            }
            node.isEnd = true;
        }
        // Returns if the word is in the trie.
        public boolean search(String word) {
            if (word == null || word.length() == 0) {
                return false;
            }
            TrieNode node = root;
            char[] letters = word.toCharArray();
            for (int i = 0; i < word.length(); i++) {
                int pos = letters[i] - 'a';
                if (node.son[pos] != null) {
                    node = node.son[pos];
                } else {
                    return false;
                }
            }
            return node.isEnd;
        }
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            if (prefix == null || prefix.length() == 0) {
                return false;
            }
            TrieNode node = root;
            char[] letters = prefix.toCharArray();
            for (int i = 0; i < prefix.length(); i++) {
                int pos = letters[i] - 'a';
                if (node.son[pos] != null) {
                    node = node.son[pos];
                } else {
                    return false;
                }
            }
            return true;
        }
    }
    class TrieNode {
        // Initialize your data structure here.
        TrieNode[] son;// 所有的儿子节点
        boolean isEnd;// 是不是最后一个节点
        char val;// 节点的值
        TrieNode() {
            this.son = new TrieNode[26];
            this.isEnd = false;
        }
    }
  • 相关阅读:
    Ubuntu在命令行开启远程桌面
    Qt5编译项目出现GL/gl.h:No such file or directory错误
    硬盘录像机协议与技术汇总
    js判断IP字符串是否正确
    PHP获取原生POST数据
    hdu 5093 二分匹配
    hdu 4435 bfs+贪心
    hdu 4431 绝对值之和最小公式
    hdu 5073 推公式相邻质心转换
    hdu 3657 最小割(牛逼!!!!)总算理解了
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5573285.html
Copyright © 2011-2022 走看看