|
| 1 | +// GPT์ ํ์ด. ํธ๋ฆฌ๋ฅผ ์ด์ฉํด O(m)์ผ๋ก ํด๊ฒฐํ๋ค. |
| 2 | +public class Trie { |
| 3 | + private class TrieNode { |
| 4 | + TrieNode[] children; |
| 5 | + boolean isEndOfWord; |
| 6 | + |
| 7 | + public TrieNode() { |
| 8 | + children = new TrieNode[26]; // ์ํ๋ฒณ a~z (26๊ฐ์ ์์ ๋
ธ๋) |
| 9 | + isEndOfWord = false; // ํด๋น ๋
ธ๋๊ฐ ๋จ์ด์ ๋์ธ์ง ์๋์ง ๋ํ๋ |
| 10 | + } |
| 11 | + } |
| 12 | + |
| 13 | + private TrieNode root; |
| 14 | + |
| 15 | + public Trie() { |
| 16 | + root = new TrieNode(); // ๋ฃจํธ ๋
ธ๋ ์ด๊ธฐํ |
| 17 | + } |
| 18 | + |
| 19 | + public void insert(String word) { |
| 20 | + TrieNode node = root; |
| 21 | + for (char c : word.toCharArray()) { |
| 22 | + int index = c - 'a'; // ์ํ๋ฒณ์ 0-25์ ์ซ์๋ก ๋ณํ |
| 23 | + if (node.children[index] == null) { |
| 24 | + node.children[index] = new TrieNode(); // ํด๋น ๋ฌธ์๊ฐ ์์ผ๋ฉด ์ ๋
ธ๋๋ฅผ ์์ฑ |
| 25 | + } |
| 26 | + node = node.children[index]; // ์์ ๋
ธ๋๋ก ์ด๋ |
| 27 | + } |
| 28 | + node.isEndOfWord = true; // ๋จ์ด์ ๋์ ํ์ |
| 29 | + } |
| 30 | + |
| 31 | + public boolean search(String word) { |
| 32 | + TrieNode node = root; |
| 33 | + for (char c : word.toCharArray()) { |
| 34 | + int index = c - 'a'; |
| 35 | + if (node.children[index] == null) { |
| 36 | + return false; // ํด๋น ๋ฌธ์๊ฐ ์์ผ๋ฉด false ๋ฐํ |
| 37 | + } |
| 38 | + node = node.children[index]; // ์์ ๋
ธ๋๋ก ์ด๋ |
| 39 | + } |
| 40 | + return node.isEndOfWord; // ๋จ์ด์ ๋์ธ์ง๋ฅผ ํ์ธ |
| 41 | + } |
| 42 | + |
| 43 | + public boolean startsWith(String prefix) { |
| 44 | + TrieNode node = root; |
| 45 | + for (char c : prefix.toCharArray()) { |
| 46 | + int index = c - 'a'; |
| 47 | + if (node.children[index] == null) { |
| 48 | + return false; // ํด๋น ์ ๋์ฌ๋ก ์์ํ๋ ๋จ์ด๊ฐ ์์ผ๋ฉด false ๋ฐํ |
| 49 | + } |
| 50 | + node = node.children[index]; // ์์ ๋
ธ๋๋ก ์ด๋ |
| 51 | + } |
| 52 | + return true; // ์ ๋์ฌ๋ก ์์ํ๋ ๋จ์ด๊ฐ ์์ผ๋ฉด true ๋ฐํ |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// ๋ฐฑํธ๋ํน์ผ๋ก ํ์ด๋ดค๋๋ฐ, ์๋๊ฐ ๋๋ฌด ์๋์์ |
| 57 | +// O(n*m)์ ์๊ฐ๋ณต์ก๋๊ฐ ๋์ด. n์ ๊ธ์์ m์ ๊ธ์๊ธธ์ด |
| 58 | +class Trie { |
| 59 | + |
| 60 | + private List<String> words; |
| 61 | + |
| 62 | + public Trie() { |
| 63 | + words = new ArrayList<>(); |
| 64 | + } |
| 65 | + |
| 66 | + public void insert(String word) { |
| 67 | + words.add(word); |
| 68 | + } |
| 69 | + |
| 70 | + public boolean search(String word) { |
| 71 | + return backtrack(word, true); |
| 72 | + } |
| 73 | + |
| 74 | + public boolean startsWith(String prefix) { |
| 75 | + return backtrack(prefix, false); |
| 76 | + } |
| 77 | + |
| 78 | + private boolean backtrack(String target, boolean exactMatch) { |
| 79 | + for (String word : words) { |
| 80 | + if (exactMatch) { |
| 81 | + if (word.equals(target)) { |
| 82 | + return true; |
| 83 | + } |
| 84 | + } else { |
| 85 | + if (word.startsWith(target)) { |
| 86 | + return true; |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + return false; |
| 91 | + } |
| 92 | +} |
0 commit comments