Java实现 LeetCode 720 词典中最长的单词(字典树)

720. 词典中最长的单词

给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。

若无答案,则返回空字符串。

示例 1:

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

输入:
words = [“a”, “banana”, “app”, “appl”, “ap”, “apply”, “apple”]
输出: “apple”
解释:
“apply"和"apple"都能由词典中的单词组成。但是"apple"得字典序小于"apply”。
注意:

所有输入的字符串都只包含小写字母。
words数组长度范围为[1,1000]。
words[i]的长度范围为[1,30]。

class Solution {
     class Node{
        String val;
        Node[] next;
        Node(){
            val=null;
            next=new Node[26];
        }
    }
    Node root;
    String res;
    //建树
    private void build(String[] words){
        for(String word:words)
            buildTrie(word.toCharArray(),0,root);
    }
    private void buildTrie(char[] word,int pos,Node cur){
        if(cur.next[word[pos]-'a']==null)
            cur.next[word[pos]-'a']=new Node();
        cur=cur.next[word[pos]-'a'];
        if(pos+1==word.length){
            cur.val=new String(word);
            return;
        }
        buildTrie(word,pos+1,cur);    
    }
    //查找树
    private void preorder(Node cur){
        if(cur.val.length()>res.length())
            res=cur.val;
        for(int i=0;i<26;i++)
            if(cur.next[i]!=null&&cur.next[i].val!=null)
                preorder(cur.next[i]);
        // if(cur!=null){
        //     System.out.println(cur.val);
        //     for(int i=0;i<26;i++)
        //     preorder(cur.next[i]);
        // }
    }
    public String longestWord(String[] words) {
        root=new Node();
        root.val="";
        res="";
        build(words);
        preorder(root);
        return res;
    }
}
发布了1767 篇原创文章 · 获赞 3万+ · 访问量 401万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/105412668
720