LeetCode之Trie题目汇总
2015-12-30 10:28
274 查看
Implement Trie (Prefix Tree)
Implement a trie withinsert,
search, and
startsWithmethods.
Note:
You may assume that all inputs are consist of lowercase letters
a-z.
[code] class TrieNode { boolean isLeaf; char c; HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>(); // Initialize your data structure here. public TrieNode() { } public TrieNode(char c) { this.c = c; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { HashMap<Character, TrieNode> children = root.children; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); TrieNode t; if (children.containsKey(c)) { t = children.get(c); } else { t = new TrieNode(c); children.put(c, t); } children = t.children; if (i == word.length() - 1) { t.isLeaf = true; } } } // Returns if the word is in the trie. public boolean search(String word) { HashMap<Character, TrieNode> children = root.children; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (!children.containsKey(c)) { return false; } if (i == word.length() - 1) { if (children.get(c).isLeaf == true) { return true; } return false; } children = children.get(c).children; } // useless return false; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { HashMap<Character, TrieNode> children = root.children; for (int i = 0; i < prefix.length(); i++) { char c = prefix.charAt(i); if (!children.containsKey(c)) { return false; } if (i == prefix.length() - 1) { return true; } children = children.get(c).children; } // useless return false; } } // Your Trie object will be instantiated and called as such: // Trie trie = new Trie(); // trie.insert("somestring"); // trie.search("key");
相关文章推荐
- mysql查询今天、昨天、7天、近30天、本月、上一月 数据
- shell脚本超时控制
- 日本京瓷株式会社会长-稻盛和夫寄语汇总
- supervisor运行python程序时的环境配置
- UpdateData(TRUE)和UpdateData(FALSE)的区别
- opengl简单视频教程
- opencv 读取摄像头失败
- KafkaOffsetMonitor 安装
- 百度导航--总结
- textarea 多行文本保存数据到DB,取出后恢复换行
- linux 添加用户、权限
- Win7 、Win8局域网共享详细教程
- Ubuntu安装Docker引擎和支持HTTPS的docker-registry服务
- 【Tomcat】配置多网站(使用80端口)
- 模拟退火
- ubuntu下屏幕录像,截屏
- FLV科普8 FLV音频头信息
- jQuery源码分析13--仿栈与队列的操作(数组的操作)
- 十个节省时间的MySQL命令
- shell 初学者 必读 ,强烈推荐新手读