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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章