Leetcode no. 208
来源:互联网 发布:淘宝怎么看同行点击率 编辑:程序博客网 时间:2024/04/29 20:50
208. Implement Trie (Prefix Tree)
Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
class TrieNode { // Initialize your data structure here. public char val; public TrieNode[] children= new TrieNode[26]; public boolean isWord; public TrieNode(){} public TrieNode(char c) { this.val= c; }}public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); root.val= ' '; } // Inserts a word into the trie. public void insert(String word) { TrieNode n= root; for (int i=0; i<word.length(); i++){ char c= word.charAt(i); if (n.children[c-'a'] ==null) n.children[c-'a']= new TrieNode(c); n= n.children[c-'a']; } n.isWord= true; } // Returns if the word is in the trie. public boolean search(String word) { TrieNode n= root; for (int i=0; i<word.length(); i++){ char c= word.charAt(i); if (n.children[c-'a'] ==null) return false; n= n.children[c-'a']; } return n.isWord; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { TrieNode n= root; for (int i=0; i<prefix.length(); i++){ char c= prefix.charAt(i); if (n.children[c-'a'] ==null) return false; n= n.children[c-'a']; } return true; }}// Your Trie object will be instantiated and called as such:// Trie trie = new Trie();// trie.insert("somestring");// trie.search("key");
0 0
- Leetcode no. 208
- Leetcode NO.208 Implement Trie (Prefix Tree)
- LeetCode No.11 ~No.12
- Leetcode NO.78 Subsets
- Leetcode NO.77 Combinations
- Leetcode NO.46 Permutations
- 【leetcode】No. 235 LCABST
- LeetCode no. 35
- Leetcode no. 37
- Leetcode no. 279
- Leetcode no. 335
- Leetcode no. 283
- Leetcode no. 181 (sql)
- Leetcode no. 40
- Leetcode no. 238
- Leetcode no. 26
- Leetcode no. 80
- Leetcode no. 228
- cocos2d-之sprite类解析
- java的变量
- 让Xcode的控制台支持LLDB类型的打印
- 学着写LUA脚本(一)
- sql语法:inner join on, left join on, right join on详细使用方法
- Leetcode no. 208
- android 基础 加密 简易加密BASE64Decoder
- Android学习系列(29)--App调试的几个命令实践
- Tomcat的部署和路径的加载
- js正则验证强密码
- nginx配置账号访问
- 度量快速开发平台:网格部件焦点行数据实现窗体功能的显示与隐藏控制
- iOS 关于UIViewAutoresizing autoresizingMask的记录
- 网站地图Sitemap.xml笔记