|
| 1 | +package io.github.dunwu.algorithm.trie; |
| 2 | + |
| 3 | +import java.util.concurrent.atomic.AtomicInteger; |
| 4 | + |
| 5 | +public class Trie { |
| 6 | + |
| 7 | + private AtomicInteger wordCount = new AtomicInteger(0); |
| 8 | + private final TrieNode root = new TrieNode('/'); // 存储无意义字符 |
| 9 | + |
| 10 | + // 往 Trie 树中插入一个字符串 |
| 11 | + public void insert(char[] text) { |
| 12 | + TrieNode p = root; |
| 13 | + for (int i = 0; i < text.length; ++i) { |
| 14 | + int index = text[i] - 'a'; |
| 15 | + if (p.children[index] == null) { |
| 16 | + TrieNode newNode = new TrieNode(text[i]); |
| 17 | + p.children[index] = newNode; |
| 18 | + } else { |
| 19 | + p.children[index].count++; |
| 20 | + } |
| 21 | + p = p.children[index]; |
| 22 | + } |
| 23 | + wordCount.getAndIncrement(); |
| 24 | + p.isEnd = true; |
| 25 | + } |
| 26 | + |
| 27 | + // 在 Trie 树中查找一个字符串 |
| 28 | + public boolean find(char[] pattern) { |
| 29 | + TrieNode p = root; |
| 30 | + for (int i = 0; i < pattern.length; ++i) { |
| 31 | + int index = pattern[i] - 'a'; |
| 32 | + if (p.children[index] == null) { |
| 33 | + return false; // 不存在 pattern |
| 34 | + } |
| 35 | + p = p.children[index]; |
| 36 | + } |
| 37 | + return p.isEnd; |
| 38 | + } |
| 39 | + |
| 40 | + public String longest() { |
| 41 | + StringBuilder sb = new StringBuilder(); |
| 42 | + for (int i = 0; i < 26; i++) { |
| 43 | + method(root.children[i], sb); |
| 44 | + } |
| 45 | + return sb.toString(); |
| 46 | + } |
| 47 | + |
| 48 | + public void method(TrieNode root, StringBuilder sb) { |
| 49 | + if (root != null) { |
| 50 | + if (root.count == wordCount.get()) { |
| 51 | + sb.append(root.data); |
| 52 | + if (root.children != null) { |
| 53 | + for (int i = 0; i < 26; i++) { |
| 54 | + method(root.children[i], sb); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + public class TrieNode { |
| 62 | + |
| 63 | + public int count; |
| 64 | + public char data; |
| 65 | + public boolean isEnd = false; |
| 66 | + public TrieNode[] children = new TrieNode[26]; |
| 67 | + |
| 68 | + public TrieNode(char data) { |
| 69 | + this.count = 1; |
| 70 | + this.data = data; |
| 71 | + } |
| 72 | + |
| 73 | + } |
| 74 | + |
| 75 | +} |
0 commit comments