[leedcode 211] Add and Search Word - Data structure design
Design a data structure that supports the following two operations:
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
public class WordDictionary { //字典树的变形,每个节点保存一个字符,以及子节点集合:list,和标记是否是尾节点的isEnd布尔值 //add和search方法都利用递归进行实现 private Node root; static class Node{ public Character val; public List<Node> children; public boolean isEnd; public Node(Character val){ this.val=val; children=new ArrayList<Node>(); isEnd=false; } } public WordDictionary(){ root=new Node('/'); } // Adds a word into the data structure. public void addWord(String word) { addword(word,root); } public void addword(String word,Node root){ if(word.length()==0){ root.isEnd=true; return ; } Node cur=null;//代表匹配的新节点 if(root.children.size()>0){ for(Node node:root.children){ if(node.val==word.charAt(0)){ cur=node; break; } } } if(cur!=null) addword(word.substring(1),cur); else { cur =new Node(word.charAt(0)); root.children.add(cur); addword(word.substring(1),cur); } } // 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 search(word,root); } private boolean search(String word,Node root){ if(word.length()==0){ return root.isEnd==true; } if(root.children==null) return false; if(word.charAt(0)=='.'){ for(Node node:root.children){ boolean ret=search(word.substring(1),node); if(ret) return true; } return false; }else{ for(Node node:root.children){ if(node.val==word.charAt(0)){ return search(word.substring(1),node); } } return false; } } } // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary = new WordDictionary(); // wordDictionary.addWord("word"); // wordDictionary.search("pattern");