标签:
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
Note:
You may assume that all words are consist of lowercase letters a-z.
public class WordDictionary {
private List<String>list=new ArrayList<>();
// Adds a word into the data structure.
public void addWord(String word) {
list.add(word);
}
// 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) {
if(list.contains(word)){
return true;
}else{
int size=list.size();
int i=0,j=0;
for(;i<size;i++){
String s= list.get(i);
int len=s.length();
if(len!=word.length())
continue;
j=0;
for(;j<len;j++){
if(word.charAt(j)==‘.‘)
continue;
else{
if(s.charAt(j)!=word.charAt(j)){
break;
}
}
}
if(j==len) return true;
}
return false;
}
}
}
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
运行结果:

方法2:按照提示,使用单词查字树
代码如下:
(*medium)LeetCode 211.Add and Search Word - Data structure design
标签:
原文地址:http://www.cnblogs.com/mlz-2019/p/4734392.html