|
| 1 | +package com.leetcode.graph; |
| 2 | + |
| 3 | +class TrieNode { |
| 4 | + // Links to child nodes |
| 5 | + private TrieNode[] links; |
| 6 | + // Marks the end of a word |
| 7 | + private boolean isEnd; |
| 8 | + |
| 9 | + public TrieNode() { |
| 10 | + links = new TrieNode[26]; // Assuming only lowercase letters |
| 11 | + isEnd = false; |
| 12 | + } |
| 13 | + |
| 14 | + public boolean containsKey(char ch) { |
| 15 | + return links[ch - 'a'] != null; |
| 16 | + } |
| 17 | + |
| 18 | + public TrieNode get(char ch) { |
| 19 | + return links[ch - 'a']; |
| 20 | + } |
| 21 | + |
| 22 | + public void put(char ch, TrieNode node) { |
| 23 | + links[ch - 'a'] = node; |
| 24 | + } |
| 25 | + |
| 26 | + public void setEnd() { |
| 27 | + isEnd = true; |
| 28 | + } |
| 29 | + |
| 30 | + public boolean isEnd() { |
| 31 | + return isEnd; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +public class Trie { |
| 36 | + private TrieNode root; |
| 37 | + |
| 38 | + public Trie() { |
| 39 | + root = new TrieNode(); |
| 40 | + } |
| 41 | + |
| 42 | + public void insert(String word) { |
| 43 | + TrieNode node = root; |
| 44 | + for (char ch : word.toCharArray()) { |
| 45 | + if (!node.containsKey(ch)) { |
| 46 | + node.put(ch, new TrieNode()); |
| 47 | + } |
| 48 | + node = node.get(ch); |
| 49 | + } |
| 50 | + node.setEnd(); |
| 51 | + } |
| 52 | + |
| 53 | + public boolean search(String word) { |
| 54 | + TrieNode node = searchPrefix(word); |
| 55 | + return node != null && node.isEnd(); |
| 56 | + } |
| 57 | + |
| 58 | + public boolean startsWith(String prefix) { |
| 59 | + TrieNode node = searchPrefix(prefix); |
| 60 | + return node != null; |
| 61 | + } |
| 62 | + |
| 63 | + private TrieNode searchPrefix(String word) { |
| 64 | + TrieNode node = root; |
| 65 | + for (char ch : word.toCharArray()) { |
| 66 | + if (node.containsKey(ch)) { |
| 67 | + node = node.get(ch); |
| 68 | + } else { |
| 69 | + return null; |
| 70 | + } |
| 71 | + } |
| 72 | + return node; |
| 73 | + } |
| 74 | + |
| 75 | + public static void main(String[] args) { |
| 76 | + Trie trie = new Trie(); |
| 77 | + trie.insert("apple"); |
| 78 | + System.out.println(trie.search("apple")); // Output: true |
| 79 | + System.out.println(trie.search("app")); // Output: false |
| 80 | + System.out.println(trie.startsWith("app")); // Output: true |
| 81 | + trie.insert("app"); |
| 82 | + System.out.println(trie.search("app")); // Output: true |
| 83 | + } |
| 84 | +} |
| 85 | + |
0 commit comments