leetcode 720. 词典中最长的单词 Trie

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Viscu/article/details/82590079

给出一个字符串数组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]。

思路:拍个序,利用字典树,将单词压入字典树中,我们先确认该单词的前n-1个字符在字典树中是否存在,
不存在直接跳出,该单词不需要压入,然后我们将第n个字符压入字典树中,并更新当前最长且字典序最小的单词。
class Solution {
    class Trie{
        Trie[] next=new Trie[26];
        Trie append(char ch){
            if(next[ch-'a']!=null){
                return next[ch-'a'];
            }
            next[ch-'a']=new Trie();
            return next[ch-'a'];
        }
    }

    public String longestWord(String[] words) {
        Arrays.sort(words);
        String str="";
        Trie root=new Trie();
        for(String cur:words){
            Trie t=root;
            for(int i=0;i<cur.length();++i){
                if(i==cur.length()-1){
                    t.next[cur.charAt(i)-'a']=new Trie();
                    if(cur.length()>str.length()){
                        str=cur;
                    }else if(cur.length()==str.length()){
                        if(cur.compareTo(str)<0){
                            str=cur;
                        }
                    }
                }
                if(t.next[cur.charAt(i)-'a']==null){
                    break;
                }else{
                    t=t.next[cur.charAt(i)-'a'];
                }
            }
        }
        return str;
    }
}

猜你喜欢

转载自blog.csdn.net/Viscu/article/details/82590079