Longest word in Dictionary

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".

思路:用trie做,可以做到O(n*L); 这题巧妙的是,build trie之后,可以bfs,层级的搜,从25往前走,那么就可以得到smallest lexicographical order.

class Solution {
    private class TrieNode {
        public TrieNode[] children;
        public boolean isword;
        public String word;
        
        public TrieNode () {
            this.children = new TrieNode[26];
            this.isword = false;
            this.word = null;
        }
    }
    
    private class Trie {
        private TrieNode root;
        public Trie () {
            root = new TrieNode();
        }
        
        public void insert(String word) {
            TrieNode cur = root;
            for(int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                if(cur.children[c - 'a'] == null) {
                    cur.children[c - 'a'] = new TrieNode();
                }
                cur = cur.children[c - 'a'];
            }
            cur.isword = true;
            cur.word = word;
        }
        
        public String findLongestWord() {
            Queue<TrieNode> queue = new LinkedList<TrieNode>();
            queue.offer(root);
            String result = null;
            
            while(!queue.isEmpty()) {
                int size = queue.size();
                for(int i = 0; i < size; i++) {
                    TrieNode node = queue.poll();
                    for(int j = 25; j >=0 ; j--) {
                        if(node != null && node.children[j] != null
                          && node.children[j].isword) {
                            result = node.children[j].word;
                            queue.offer(node.children[j]);
                        }
                    }
                }
            }
            return result;
        }
    }
    
    public String longestWord(String[] words) {
        Trie trie = new Trie();
        for(String word: words) {
            trie.insert(word);
        }
        return trie.findLongestWord();
    }
}
发布了663 篇原创文章 · 获赞 13 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/104794031