Add and Search Word - Data structure design
2015-09-29 20:26
204 查看
题意:
字典树的插入和查找
分析:
easy
参考代码:
http://www.programcreek.com/2014/05/leetcode-add-and-search-word-data-structure-design-java/
字典树的插入和查找
分析:
easy
参考代码:
http://www.programcreek.com/2014/05/leetcode-add-and-search-word-data-structure-design-java/
class TrieNode{ char c; HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>(); boolean isLeaf; public TrieNode() {} public TrieNode(char c){ this.c = c; } } public class WordDictionary { private TrieNode root; public WordDictionary(){ root = new TrieNode(); } // Adds a word into the data structure. public void addWord(String word) { HashMap<Character, TrieNode> children = root.children; for(int i=0; i<word.length(); i++){ char c = word.charAt(i); TrieNode t = null; 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 data structure. A word could // contain the dot character '.' to represent any one letter. public boolean search(String word) { return dfsSearch(root.children, word, 0); } public boolean dfsSearch(HashMap<Character, TrieNode> children, String word, int start) { if(start == word.length()){ if(children.size()==0) return true; else return false; } char c = word.charAt(start); if(children.containsKey(c)){ if(start == word.length()-1 && children.get(c).isLeaf){ return true; } return dfsSearch(children.get(c).children, word, start+1); }else if(c == '.'){ boolean result = false; for(Map.Entry<Character, TrieNode> child: children.entrySet()){ if(start == word.length()-1 && child.getValue().isLeaf){ return true; } //if any path is true, set result to be true; if(dfsSearch(child.getValue().children, word, start+1)){ result = true; } } return result; }else{ return false; } } } // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary = new WordDictionary(); // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
相关文章推荐
- HDU5492 Find a path DP
- 编程之美
- 前端开发工程师应该关注什么?
- 导航地图4_地理编码和反编码
- Arduino debug 实时单步调试.
- DevOps实战:Graphite监控上手指南
- hdu 5491 The Next(ICPC合肥赛)
- 2016华为上机题二(数字频率)
- 设置默认登陆账户
- mysql同一个表和不同表的一列复制到另一列的方法
- Crazy English on the road
- Jquery datatable jsonp 显示后台json数据
- 成员对象
- 第一次上台讲课的感受
- JdbcHelper.java(JAVA连接数据库后的备忘录的增删改查)
- Xcode 7.0 更新后 网络请求 友盟关于iOS9的一些修改
- bzoj1628: [Usaco2007 Demo]City skyline(单调队列)
- 观察者模式
- Unity3D中的一些Atrribute
- android 按两次返回键退出