[LeetCode] Longest Word in Dictionary

发布时间:2019-06-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LeetCode] Longest Word in Dictionary脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Problem

Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.

If there is no answer, return the empty string.
Example 1:
Input:

words = ["w","wo","wor","worl", "world"]

Output:

"world"

Explanation:
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input:

words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]

Output:

"apple"

Explanation:
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Note:

All the strings in the input will only contain lowercase letters.
The length of words will be in the range [1, 1000].
The length of words[i] will be in the range [1, 30].

Solution


class Solution {
    class Trie {
        Node root;
        class Node {
            boolean isWord;
            Node[] children = new Node[26];
        }
        
        public Trie() {
            root = new Node();
            root.isWord = true;
        }
        
        void insert (String str) {
            Node node = root;
            for (char ch: str.toCharArray()) {
                int index = ch - 'a';
                if (node.children[index] == null) {
                    node.children[index] = new Node();
                }
                node = node.children[index];
            }
            node.isWord = true;
        }
        
        boolean hasWord(String word) {
            Node node = root;
            for (char ch: word.toCharArray()) {
                int index = ch - 'a';
                if (node.children[index] == null || !node.isWord) return false;
                node = node.children[index];
            }
            return true;
        }
    }
    public String longestWord(String[] words) {
        Trie trie = new Trie();
        for (String word: words) {
            trie.insert(word);
        }
        String res = "";
        for (String word: words) {
            if (trie.hasWord(word) && 
               (word.length() > res.length() || (word.length() == res.length() && word.compareTo(res) < 0))) {
                res = word;
            }
        }
        return res;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LeetCode] Longest Word in Dictionary全部内容,希望文章能够帮你解决[LeetCode] Longest Word in Dictionary所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: