博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 208: Implement Trie (Prefix Tree)
阅读量:5965 次
发布时间:2019-06-19

本文共 1988 字,大约阅读时间需要 6 分钟。

class Trie {    private TrieNode root;    class TrieNode {        TrieNode[] children = new TrieNode[26];        boolean isWord;    }    /** Initialize your data structure here. */    public Trie() {        root = new TrieNode();    }        /** Inserts a word into the trie. */    public void insert(String word) {        TrieNode runner = root;        for (char c : word.toCharArray()) {            if (runner.children[(int)(c - 'a')] == null) {                runner.children[(int)(c - 'a')] = new TrieNode();            }            runner = runner.children[(int)(c - 'a')];        }        runner.isWord = true;    }        /** Returns if the word is in the trie. */    public boolean search(String word) {        TrieNode runner = root;        for (char c : word.toCharArray()) {            if (runner.children[(int)(c - 'a')] == null) {                return false;            }            runner = runner.children[(int)(c - 'a')];        }        return runner.isWord;    }        /** Returns if there is any word in the trie that starts with the given prefix. */    public boolean startsWith(String prefix) {        TrieNode runner = root;        for (char c : prefix.toCharArray()) {            if (runner.children[(int)(c - 'a')] == null) {                return false;            }            runner = runner.children[(int)(c - 'a')];        }                return isWords(runner);    }        private boolean isWords(TrieNode node) {        if (node == null) {            return false;        }                if (node.isWord) {            return true;        }                for (TrieNode child : node.children) {            if (isWords(child)) {                return true;            }        }        return false;    }}/** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */

 

转载于:https://www.cnblogs.com/shuashuashua/p/7443243.html

你可能感兴趣的文章
HashMap的底层实现
查看>>
NTP同步时间
查看>>
Oracle 11gR2 RAC OCR和votingdisk故障恢复案例
查看>>
Win10,Win7,WinServer2012,WinServer2008内存最大支持
查看>>
VMware VSphere 引发的学案(三)
查看>>
android aidl和普通service
查看>>
Flashlight should be gray after finishing Recor...
查看>>
用面向对象的方式来编写javascript
查看>>
Windows Phone 7 自定义弹出窗口
查看>>
AIX 系统下做 rootvg
查看>>
I/O读写的另一种方式-NIO
查看>>
proxychains 一个好用的终端用代理拦截器
查看>>
How to Install MariaDB 10 on CentOS 6.7
查看>>
vue-lazyload vue图片懒加载插件的使用记录
查看>>
java.lang.UnsupportedClassVersionError
查看>>
centos 5.4 nfs服务器搭建
查看>>
jquery获取父级元素和子级元素
查看>>
Delphi 调用Domino Lotus OA
查看>>
定时压缩log日志文件
查看>>
[yum]Another app is currently holding the yum lock
查看>>