码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Add and Search Word - Data structure design

时间:2015-05-16 14:54:18      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:

package leetcode;import java.util.ArrayList;import java.util.List;public class WordDictionary {private Node root;public WordDictionary(){root = new Node(‘/‘);}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 - Data structure design

标签:

原文地址:http://blog.csdn.net/muti_tt/article/details/45767977

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!