211. Add and Search Word - Data structure design
2016-07-22 23:45
281 查看
就是trie
68行那里要return false因为在62行处,可能没有结果,开始写成true死都调不出来
public class WordDictionary { public class TrieNode { public TrieNode[] child; public char curChar; public boolean isLeaf; public TrieNode() { child = new TrieNode[26]; isLeaf = false; } } TrieNode root; public WordDictionary() { root = new TrieNode(); } // Adds a word into the data structure. public void addWord(String word) { if(word.length() == 0) { return; } TrieNode curNode = root; for(int i = 0; i < word.length(); i++) { char cur = word.charAt(i); int index = cur - 'a'; if(curNode.child[index] == null) { curNode.child[index] = new TrieNode(); curNode.child[index].curChar = cur; } curNode = curNode.child[index]; } curNode.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) { if(word.length() == 0) { return true; } return searchHelper(word, root); } private boolean searchHelper(String word, TrieNode curNode) { if(word.length() == 0) { return curNode.isLeaf; } char cur = word.charAt(0); String sub = word.substring(1); if(cur != '.') { int index = cur - 'a'; if(curNode.child[index] == null) { return false; } if(curNode.child[index].curChar != cur) { return false; } return searchHelper(sub, curNode.child[index]); } else { for(int i = 0; i < 26; i++) { if(curNode.child[i] != null && searchHelper(sub, curNode.child[i])) { return true; } } } return false; } }
68行那里要return false因为在62行处,可能没有结果,开始写成true死都调不出来
相关文章推荐
- 一个操作系统的实现中关于64位和32位的问题
- hdu 3440 House Man(差分约束)
- 合并两个排序的链表 C++
- 【杭电 1789 】Doing Homework again
- tomcat启动startup.bat一闪而过
- 内核打印杂谈
- 20 个 CSS 高级技巧汇总
- hdu 5744(想法题)
- javaee之cookie和session的见解和练习
- 15个你不可不知的cmd命令
- Codeforces 698A: Vacations(贪心)
- 为什么要内存对齐
- Morphia 学习一 注解
- 剑指offer——和为s的连续正数序列
- 7月22日实习日志及总结
- Tomcat单机多实例配置
- OGRE的安装与配置(windows)
- Zabbix监控Mysql数据库性能
- CodeForces 610A Pasha and Stick (拆数字组成长方形)
- 棋盘分割