[LeetCode 211] Add and Search word -- Data Structure Design
2015-08-25 14:07
330 查看
<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Design a data structure that supports the following two operations:</p><pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13px; padding: 9.5px; margin-top: 0px; margin-bottom: 10px; line-height: 1.42857143; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; border: 1px solid rgb(204, 204, 204); border-radius: 4px; background-color: rgb(245, 245, 245);">void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing only letters
a-zor
..
A
.means it can represent any one letter.
For example:
addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters
a-z.
利用trie prefix tree。
TreeNode root = new TreeNode(); // Adds a word into the data structure. public void addWord(String word) { Map<Character, TreeNode> children = root.children; for(int i=0;i<word.length();i++){ char w = word.charAt(i); TreeNode t; if(children.containsKey(w)){ t = children.get(w); }else{ t = new TreeNode(w); children.put(w, t); } children = t.children; if(i == word.length()-1) t.leaf = true; } } public boolean searchNode(String word, TreeNode node){ if(node == null) return false; if(word.isEmpty()) return node.leaf; Map<Character, TreeNode> children = node.children; char c = word.charAt(0); TreeNode t=null; if(c == '.'){ for(char key :children.keySet()){ if(searchNode(word.substring(1), children.get(key))) return true; } return false; } else if(!children.containsKey(c)){ return false; }else { t = children.get(c); return searchNode(word.substring(1), t); } } // 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 searchNode(word, root); } class TreeNode{ char c; boolean leaf=false; Map<Character, TreeNode> children = new HashMap<>(); public TreeNode (char c){ this.c = c; } public TreeNode(){ } }
相关文章推荐
- mongodb地理空间索引原理阅读摘要
- Linux find命令之exec
- cordova新建项目
- JS html 调用 js方式 js判断undefined
- 从Azure Table Storage中取数据
- 在 Databricks 可获得 Spark 1.5 预览版
- 面向接口编程详解(二)——编程实例
- nginx缓存配置和ngx_cache_purge总结
- windows下模拟鼠标点击和键盘输入
- 面向接口编程详解(二)——编程实例
- Android uses-permission 权限大全
- mysql-整合
- 所见即所得的Playground
- 海贼王片头旁白前后两篇
- Spring 3 MVC hello world example
- MDK中如何使用gnu语法--简直超实用
- 【Maven】maven工程 调试出现 Source not found ,开启jetty调试
- Xcode6 新建工程没有.pch文件
- html checkbox的使用
- [python]发送邮件(可带附件+转中文)