模板
class TrieNode {boolean isEnd; // 是否为单词末尾TrieNode[] next; // 孩子节点数组public TrieNode() {this.isEnd = false;this.next = new TrieNode[26];}
}class Trie {TrieNode root; // 虚拟头节点public Trie() {root = new TrieNode();}public void insert(String word) { // 插入单词TrieNode node = root;for (char c : word.toCharArray()) {// 先判断是否有该分支,再跳转if (node.next[c - 'a'] == null) {node.next[c - 'a'] = new TrieNode();}node = node.next[c - 'a'];}node.isEnd = true; // 标记}public boolean search(String word) { // 搜索单词TrieNode node = root;// 判断每个字符是否都存在for (char c : word.toCharArray()) {node = node.next[c - 'a'];if (node == null) {return false;}}// 判断末尾return node.isEnd;}public boolean startsWith(String prefix) { // 判断前缀TrieNode node = root;for (char c : prefix.toCharArray()) {node = node.next[c - 'a'];if (node == null) {return false;}}// 走到这里就说明是前缀!!return true;}
}
@#参考
作者:wxyz
链接:https://leetcode.cn/problems/minimum-number-of-valid-strings-to-form-target-i/solutions/3022452/trie-yuan-li-tui-dao-mo-ban-tu-jie-zi-di-w1sz/