leetcode Add and Search Word - Data structure design

来源:互联网 发布:商务双肩包 知乎 编辑:程序博客网 时间:2024/06/06 12:26

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") -> falsesearch("bad") -> truesearch(".ad") -> truesearch("b..") -> true

Note:

You may assume that all words are consist of lowercase letters a-z.

这题和之前一道prefix tree前缀树思想是完全一样的,当出现.的时候我们直接遍历全部子树即可,代码:

public class WordDictionary {    TrieNode root=new TrieNode();    public void addWord(String word) {        if(word.length()==0) return;        TrieNode temp=root;       for(int i=0;i<word.length();i++){           if(temp.child[word.charAt(i)-'a']==null){               temp.child[word.charAt(i)-'a']=new TrieNode(word.charAt(i));           }           temp=temp.child[word.charAt(i)-'a'];       }        temp.isWord=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) {        return searchword(0,word,root);    }    public boolean searchword(int i,String word,TrieNode temp){        if(temp==null) return false;        if(i==word.length()) return temp.isWord==true;        if(word.charAt(i)=='.'){            for(TrieNode t:temp.child){                if(searchword(i+1,word,t)) return true;            }            return  false;        }        else        {            if(temp.child[word.charAt(i)-'a']==null) return false;            else return searchword(i+1,word,temp.child[word.charAt(i)-'a']);        }    }}class TrieNode {    // Initialize your data structure here.    public TrieNode[] child;    private char val;    public boolean isWord=false;    public TrieNode() {        this.child=new TrieNode[26];    }    public TrieNode(char s){        this.val=s;        this.child=new TrieNode[26];    }}

0 0