211. Design Add and Search Words Data Structure
Design a data structure that supports adding new words and finding if a string matches any previously added string.
WordDictionary
class:WordDictionary()
Initializes the object.void addWord(word)
Adds word to the data structure, it can be matched later.bool search(word)
Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots .
where dots can be matched with any letter.기본 전략
Trie 구현
void addWord(word)
null
이 아니라면, 재귀적으로 insert(substring)을 하고, null
이라면 새로 만들어서 넣은 후에 재귀적으로 insert(substring)을 요청한다.bool search(word)
.
인 경우, 모든 하위 Node를 search(substring)
을 한다.class WordDictionary {
private final Trie trie = new Trie();
public WordDictionary() {
}
public void addWord(String word) {
trie.insert(word);
}
public boolean search(String word) {
return trie.search(word);
}
class Trie {
private static final int COUNT_OF_LETTERS = 26;
private static final char START_LETTER = 'a';
private static final char ALL_LETTER = '.';
private final Trie[] children;
private boolean isEnd;
public Trie() {
children = new Trie[COUNT_OF_LETTERS];
isEnd = false;
}
public void insert(String word) {
if (word.length() == 0) {
isEnd = true;
return;
}
Trie child = getChild(word);
if (child == null) {
child = putNewChild(word);
}
child.insert(word.substring(1));
}
public boolean search(String word) {
if (word.length() == 0) {
return isEnd;
}
if (word.charAt(0) != ALL_LETTER) {
Trie child = getChild(word);
return child != null && child.search(word.substring(1));
}
for (Trie child : children) {
if (child != null && child.search(word.substring(1))) {
return true;
}
}
return false;
}
private Trie getChild(String word) {
char key = word.charAt(0);
return children[key - START_LETTER];
}
private Trie putNewChild(String word) {
char key = word.charAt(0);
Trie child = new Trie();
children[key - START_LETTER] = child;
return child;
}
}
}