λ¬Έμ νμ
νΉμ λ¬Έμμ΄μ 보κ΄νκ³ search
νμ λ, μ‘΄μ¬νλ©΄ true
λ₯Ό λ°ννλ μλ£κ΅¬μ‘°λ₯Ό λ§λ€μ΄μΌνλ€.
.
μ΄ ν¬ν¨λ κ²½μ°λ μ΄λ ν λ¬Έμκ° λ€μ΄κ°λ νμ©λλ€.
νμ΄
1οΈβ£ Trie μλ£κ΅¬μ‘°λ₯Ό μ΄μ©ν νμ΄
π‘ λ μ€λ₯Έ IdeaTrie
μλ£κ΅¬μ‘°λ₯Ό μ΄μ©νλ©΄ μ λμ΄λ λΆλΆ λ¬Έμμ΄μ κ²μν μ μλ€.
λ°λΌμ,Trie
μλ£κ΅¬μ‘°λ₯Ό ꡬννμλ€.
νΉν, μ΄ λ¬Έμ μμλsearch
κ³Όμ μμ.
μ΄ ν¬ν¨λμ΄ μλ κ²½μ°λ
ν΄λΉ λ Έλκ° κ°λ λͺ¨λ μμ λ Έλλ€μ νμνλλ‘ κ΅¬ννμ¬ ν΄κ²°ν μ μμ κ²μ΄λΌ νλ¨νμλ€.
import java.util.*;
class WordDictionary {
static class Node {
Map<Character, Node> children;
boolean isEndOfWord;
public Node() {
this.children = new HashMap<>();
this.isEndOfWord = false;
}
}
Node root;
public WordDictionary() {
root = new Node();
}
public void addWord(String word) {
addWord(this.root, word);
}
private void addWord(Node node, String word) {
if (word.length() == 0) {
node.isEndOfWord = true;
return;
}
char ch = word.charAt(0);
Node child;
if (node.children.containsKey(ch)) {
child = node.children.get(ch);
} else {
child = new Node();
node.children.put(ch, child);
}
addWord(child, word.substring(1));
}
public boolean search(String word) {
return search(this.root, word);
}
private boolean search(Node node, String word) {
if (word.length() == 0) {
return node.isEndOfWord;
}
char ch = word.charAt(0);
if (ch == '.') {
for (Node child : node.children.values()) {
if (search(child, word.substring(1))) {
return true;
}
}
return false;
}
if (!node.children.containsKey(ch)) {
return false;
} else {
return search(node.children.get(ch), word.substring(1));
}
}
}
κ²°κ³Ό
π νκ³
Trie μλ£κ΅¬μ‘°μ κ°μ₯ ν° νΉμ§ μ€μ νλμΈ λΆλΆ λ¬Έμμ΄ κ²μμ μ§μ ꡬνν΄λ³Ό μ μλ λ¬Έμ μλ€.
λ€λ₯Έ μ½λλ₯Ό μ°Έκ³ νμ§ μκ³ μ§μ ꡬννλ©΄μ, λμ λ©μ»€λμ¦μ μ΄ν΄ν μ μμλ€.