Leecode no.211 添加与搜索单词

package leecode;

/**
* @Author:tang
* @CreateDate 2021/5/12
*
* 请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
*
* WordDictionary() 初始化词典对象
* void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配
* bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回 false 。word 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。
*/
public class WordDictionary {

char[] dict;

StringBuilder words;

WordDictionary(){
words = new StringBuilder();
}

void addWord(String word){
words.append(word);
}

boolean search(String word){
dict = words.toString().toCharArray();
for(int i = 0; i < dict.length-word.length()+1; i++){
if(matching(i, 0, word.toCharArray())){
return true;
}
}
return false;
}

/**
* 比较开始字典 与word能否完全匹配
* @param indexDict
* @param indexWord
* @param words
* @return
*/
private boolean matching(int indexDict, int indexWord, char[] words){
if(indexWord > words.length -1){
return true;
}
if(indexDict > dict.length -1){
return false;
}
if(dict[indexDict] == words[indexWord] || words[indexWord] == '.'){
return matching(indexDict +1, indexWord +1, words);
}
return false;
}

public static void main(String[] args) {

WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("a");
wordDictionary.addWord("a");
//wordDictionary.addWord("found");
System.out.println(wordDictionary.search("a"));
System.out.println(wordDictionary.search("aa"));
System.out.println(wordDictionary.search("."));
System.out.println(wordDictionary.search("a."));
System.out.println(wordDictionary.search(".a"));
}

}
posted @ 2021-05-18 17:08  六小扛把子  阅读(49)  评论(0编辑  收藏  举报