Implement Trie (Prefix Tree) ——LeetCode
2015-07-27 18:09
465 查看
Implement a trie with
Note:
You may assume that all inputs are consist of lowercase letters
实现一个字典树。
好久不做题,没感觉啊,TreeNode用一个布尔变量表示是否是一个合法单词的结尾即可,一开始还用cnt来计数,search的时候比较麻烦。
insert,
search, and
startsWithmethods.
Note:
You may assume that all inputs are consist of lowercase letters
a-z.
实现一个字典树。
好久不做题,没感觉啊,TreeNode用一个布尔变量表示是否是一个合法单词的结尾即可,一开始还用cnt来计数,search的时候比较麻烦。
class TrieNode { // Initialize your data structure here. TrieNode [] next; boolean valid; public TrieNode() { next = new TrieNode[26]; valid=false; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { TrieNode ptr = root; for(char c:word.toCharArray()){ if(ptr.next[c-'a']==null){ ptr.next[c-'a'] = new TrieNode(); } ptr=ptr.next[c-'a']; } ptr.valid=true; } // Returns if the word is in the trie. public boolean search(String word) { int last = 0; TrieNode ptr = root; for(char c:word.toCharArray()){ if(ptr==null||ptr.next[c-'a']==null){ return false; } ptr=ptr.next[c-'a']; } return ptr.valid; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode ptr = root; for(char c:prefix.toCharArray()){ if(ptr==null||ptr.next[c-'a']==null){ return false; } ptr=ptr.next[c-'a']; } return true; } } // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- navicat的注册和安装问题
- 浅谈数组与指针表示字符串的区别
- HTML—超文本标记语言
- 【二分图匹配】zoj1002Fire Net
- System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration sect
- Python实现删除当前目录下除当前脚本以外的文件和文件夹实例
- git操作分支
- LeetCode_105 Construct Binary Tree from Preorder and Inorder Traversal
- 注入式开发
- System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration sect
- code Gym 100500D T-shirts(暴力)
- .NET学习笔记 -- 那堆名词到底是啥(CLR、CLI、CTS、CLS、IL、JIT)
- 注入式开发
- oracle 任务使用
- JavaScript中的Repaint和Reflow用法详解
- breeze densematrix 基本操作
- apache worker性能调优
- Codeforces 557E - Ann and Half-Palindrome (字典树+DP)
- 短信拦截再总结
- 使用Spring Boot和Gradle创建AngularJS项目