Leetcode Add and Search Word

package leetcode;import java.util.ArrayList;import java.util.List;public class WordDictionary {private Node root;public WordDictionary(){root = new Node(‘http://blog.csdn.net/’);}static class Node{public Character val;public List children;public boolean isEnd;public Node(Character val){this.val = val;children = null;isEnd = false;}}public void insert(String word,int curIndex,Node curNode){ if(curIndex == word.length()){ return; } if(curNode.children == null){ List tmp = new ArrayList(); Node cur = new Node(word.charAt(curIndex)); if(curIndex == word.length() – 1){ cur.isEnd = true; } tmp.add(cur); curNode.children = tmp; insert(word,curIndex+1,cur); return; } // boolean flag = true; Node cur = null; for(Node node : curNode.children){ if(node.val == word.charAt(curIndex)){ cur = node; break; } } if(cur == null){ cur = new Node(word.charAt(curIndex)); curNode.children.add(cur); } if(curIndex == word.length() -1){ cur.isEnd = true; } insert(word,curIndex+1,cur); return;}public boolean search(String word,int curIndex,Node curNode){if(curIndex == word.length()){if(curNode.isEnd &&(word.charAt(curIndex -1 ) == ‘.’ || curNode.val == word.charAt(curIndex -1))){return true;}return false;}if(curNode.children == null){return false;}if(word.charAt(curIndex) == ‘.’){for(Node node : curNode.children){if(search(word,curIndex + 1,node)){return true;}}}else{for(Node node : curNode.children){if(node.val == word.charAt(curIndex) && search(word,curIndex + 1,node)){return true;}}}return false;}/** * * @param word */public void addWord(String word){if(word == null || word.trim().length() == 0 )return;insert(word,0,root);}/** * * @param word * @return */public boolean search(String word){if(word == null || word.length() == 0)return false;return search(word,0,root);}public static void main(String []args){WordDictionary wd = new WordDictionary();wd.addWord("bad");wd.addWord("dad");wd.addWord("mad");wd.addWord("bat");System.out.println(wd.search("pad"));System.out.println(wd.search("bad"));System.out.println(wd.search(".ad"));System.out.println(wd.search("b.."));System.out.println(wd.search("bat"));}}

,而只有在充满了艰辛的人生旅途中,始终调整好自己观风景的心态,

Leetcode Add and Search Word

相关文章:

你感兴趣的文章:

标签云: