LeetCode Add and Search Word - Data structure design Trie
2015-11-12 09:57
513 查看
思路:
根据hint应该用trie树,否则肯定超时。
java code:
根据hint应该用trie树,否则肯定超时。
java code:
public class WordDictionary { class TrieNode { boolean isLeaf; TrieNode[] children = new TrieNode[26]; public TrieNode() { } } private TrieNode root = new TrieNode(); // Adds a word into the data structure. public void addWord(String word) { TrieNode node = root; for(char c : word.toCharArray()) { if(node.children[c - 'a'] == null) { node.children[c - 'a'] = new TrieNode(); } node = node.children[c - 'a']; } node.isLeaf = true; } // Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. private boolean dfs(String word, TrieNode cur) { if(cur == null) return false; if(word.length() == 0) return cur.isLeaf; TrieNode[] children = cur.children; char c = word.charAt(0); if(c == '.') { for(TrieNode child : children) { if(child != null && dfs(word.substring(1), child)) { return true; } } return false; }else if(children[c - 'a'] != null) { return dfs(word.substring(1), children[c - 'a']); }else { return false; } } public boolean search(String word) { return dfs(word, root); } }
相关文章推荐
- HDU 4888 Redraw Beautiful Drawings 网络流(矩阵模型)
- 圆的面积
- JSP自定义标签开发入门
- Android 中三种使用线程的方法
- mysql性能监控相关
- AndroidManifest.xml文件详解(uses-feature)
- 06(maven+SSH)网上商城项目实战之springmvc配置
- Mysql修复损坏表并写脚本自动修复
- 轻松让您的visio2010 支持正向工程
- 勾股定理
- 1020. 月饼 (25)
- 简单了解weblogic配置文件
- Linux动态库相关知识整理
- Synchronization Service Manager
- 你还在我身旁
- T013 找素数求和
- 20个最佳的Java集合框架面试题目
- SAP损益类科目余额结转到未分配利润科目
- mysql基础教程(1)---视图
- 计算组合数