Add and Search Word - Data structure design
2015-08-17 21:05
375 查看
Design a data structure that supports the following two operations:
search(word) can search a literal word or a regular expression string containing
only letters a-z or .. A . means it can represent any one letter.
For example:
与上一题相似,同样用到Trie Node,不同之处是search时,.号需要遍历DFS匹配。
void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing
only letters a-z or .. 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
与上一题相似,同样用到Trie Node,不同之处是search时,.号需要遍历DFS匹配。
public class WordDictionary { 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; TrieNode tmp; for(int i=0;i<word.length();i++){ char c=word.charAt(i); if(children.containsKey(c)){ tmp=children.get(c); }else{ tmp=new TrieNode(c); children.put(c, tmp); } children=tmp.children; if(i==word.length()-1) tmp.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) { HashMap<Character,TrieNode> children=root.children; return bfs(children,word,0); } private boolean bfs(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 bfs(children.get(c).children,word,start+1); }else if(c=='.'){ boolean result=false; for(Map.Entry<Character, TrieNode> t:children.entrySet()){ if(start==word.length()-1&&t.getValue().isLeaf) return true; if(bfs(t.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");
相关文章推荐
- LeetCode之Unique Binary Search Trees II
- WAMP虚拟主机配置
- Cocos2d-x学习笔记(十二)—— Box2d物理引擎(未完)
- 第一个小练习,从基础重新来
- ORACLE- PLSQL Developer 远程连接oracle数据库 4000
- Eclipse初体验
- BFS-HDU-2612-Find a Way
- Html本地数据存储Web Storage
- jQuery 表单数据序列化为json格式
- Dining
- matlab#1软件基本操作
- 【Android】四大组件(3)Service
- java双缓冲 笔记
- 题目-协议
- iOS开发——多线程篇——GCD
- find the safest road
- fatal: could not read Username for 'https://github.com': No such file or directo
- hdu1162 Eddy's picture 并查集+最小生成树
- IOS-笔记5 (swift和OC,View大小和位置)
- ubuntu下mysql安装(server、client、dev),开启、停止和重启,及常见错误