|
| 1 | +/** |
| 2 | + * 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. |
| 3 | + * |
| 4 | + * If there is no answer, return the empty string. |
| 5 | + * Example 1: |
| 6 | + * Input: |
| 7 | + * words = ["w","wo","wor","worl", "world"] |
| 8 | + * Output: "world" |
| 9 | + * Explanation: |
| 10 | + * The word "world" can be built one character at a time by "w", "wo", "wor", and "worl". |
| 11 | + * Example 2: |
| 12 | + * Input: |
| 13 | + * words = ["a", "banana", "app", "appl", "ap", "apply", "apple"] |
| 14 | + * Output: "apple" |
| 15 | + * Explanation: |
| 16 | + * Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply". |
| 17 | + * Note: |
| 18 | + * |
| 19 | + * All the strings in the input will only contain lowercase letters. |
| 20 | + * The length of words will be in the range [1, 1000]. |
| 21 | + * The length of words[i] will be in the range [1, 30]. |
| 22 | + */ |
| 23 | +public class Leetcode_720_140 { |
| 24 | + |
| 25 | + class TrieNode{ |
| 26 | + char val; |
| 27 | + TrieNode[] next; |
| 28 | + boolean isWord; |
| 29 | + TrieNode(char val){ |
| 30 | + this.val = val; |
| 31 | + next = new TrieNode[26]; |
| 32 | + isWord = false; |
| 33 | + } |
| 34 | + } |
| 35 | + public String longestWord(String[] words) { |
| 36 | + TrieNode root = new TrieNode(' '); |
| 37 | + for(String str: words){ |
| 38 | + buildTree(root, str); |
| 39 | + } |
| 40 | + int max = 0; |
| 41 | + int index = -1; |
| 42 | + for(int i = 0; i < words.length; i++){ |
| 43 | + String str = words[i]; |
| 44 | + boolean flag = findWord(root, str); |
| 45 | + if(flag && str.length() > max){ |
| 46 | + max = str.length(); |
| 47 | + index = i; |
| 48 | + } |
| 49 | + if(flag && str.length() == max){ |
| 50 | + String old = words[index]; |
| 51 | + index = str.compareTo(old) < 0 ? i : index; |
| 52 | + } |
| 53 | + } |
| 54 | + return words[index]; |
| 55 | + } |
| 56 | + private void buildTree(TrieNode root, String str){ |
| 57 | + for(char c : str.toCharArray()){ |
| 58 | + if(root.next[c - 'a'] == null){ |
| 59 | + root.next[c - 'a'] = new TrieNode(c); |
| 60 | + } |
| 61 | + root = root.next[c - 'a']; |
| 62 | + } |
| 63 | + root.isWord = true; |
| 64 | + } |
| 65 | + private boolean findWord(TrieNode root, String str){ |
| 66 | + for(int i = 0; i < str.length(); i++){ |
| 67 | + char c = str.charAt(i); |
| 68 | + if(root.next[c - 'a'] == null){ |
| 69 | + return false; |
| 70 | + } |
| 71 | + root = root.next[c - 'a']; |
| 72 | + if(!root.isWord) { |
| 73 | + return false; |
| 74 | + } |
| 75 | + } |
| 76 | + return true; |
| 77 | + } |
| 78 | + |
| 79 | +} |
0 commit comments