720--词典中最长的单词(字典树)

题目

给出一个字符串数组 words 组成的一本英语词典。返回 words 中最长的一个单词,该单词是由 words 词典中其他单词逐步添加一个字母组成。

若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。

示例 1:

输入:words = ["w","wo","wor","worl", "world"]
输出:"world"
解释: 单词"world"可由"w", "wo", "wor", 和 "worl"逐步添加一个字母组成。

思路

利用字典树,首先构建字典树,构建结点,每一个结点都是有一个字符,有一个hashTable用来存储自己的children,构建一个字典树。利用dfs进行读。

题解

点击查看代码
class Solution {
    public String longestWord(String[] words) {
        Tree tree=new Tree();
        int index=0;
        for (String word : words) {
            tree.insert(word,++index);
        }
        tree.words=words;
        return tree.dfs();
    }
}
class Node{
    char c;
    HashMap<Character,Node> children=new HashMap<>();
    int end;
    public Node(char c){
        this.c=c;
    }
}
class Tree{
    Node root;
    String [] words;
    public Tree(){
        root=new Node('0');
    }
    public void insert(String word,int index){
        Node cur=root;
        for (char c: word.toCharArray()) {
            cur.children.putIfAbsent(c, new Node(c));
            cur = cur.children.get(c);
        }
        cur.end=index;
    }
    public String dfs(){
        String ans="";
        Stack<Node> stack=new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            Node node=stack.pop();
            if(node.end>0||node==root){
                if(node!=root){
                    String word=words[node.end-1];
                    if(word.length()>ans.length()||word.length()==ans.length()&&word.compareTo(ans) < 0){
                        ans=word;
                    }
                }
                for(Node nei:node.children.values()){
                    stack.push(nei);
                }
            }
        }
        return ans;
    }
    
}

posted @   是徐洋洋呀  阅读(64)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示