中级农民
- 积分
- 102
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2024-11-5
- 最后登录
- 1970-1-1
|
代码写的可读性太低了,一个精简版- import java.util.*;
- class TrieNode {
- Map<Character, TrieNode> children;
- boolean isWord;
- public TrieNode() {
- children = new HashMap<>();
- isWord = false;
- }
- }
- class Trie {
- TrieNode root;
- public Trie() {
- this.root = new TrieNode();
- }
- public void insert(String word) {
- TrieNode cur = root;
- for (char c : word.toCharArray()) {
- cur.children.putIfAbsent(c, new TrieNode());
- cur = cur.children.get(c);
- }
- cur.isWord = true;
- }
- public boolean hasChildren(String word) {
- TrieNode cur = root;
- for (char c : word.toCharArray()) {
- cur = cur.children.get(c);
- }
- return !cur.children.isEmpty();
- }
- }
- public class RemovePrefix {
- public static void main(String[] args) {
- System.out.println(removePrefix(Arrays.asList("a", "b", "ab", "abc"))); // Output: [b, abc]
- System.out.println(removePrefix(Arrays.asList("a", "ab", "abc", "abcd"))); // Output: [abcd]
- System.out.println(removePrefix(Arrays.asList("abc", "def", "abcd", "de"))); // Output: [abc, def, abcd]
- }
- private static List<String> removePrefix(List<String> words) {
- Trie trie = new Trie();
- // Build the Trie with all words
- for (String w : words) {
- trie.insert(w);
- }
- List<String> res = new ArrayList<>();
- for (String w : words) {
- // Only add the word if it is not a prefix of another word
- if (!trie.hasChildren(w)) {
- res.add(w);
- }
- }
- return res;
- }
- }
复制代码 |
|