[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;
}
}
Road to Glory
[LeetCode] 958. Check Completeness of a Binary Tree
linspiration阅读 1.9k
Java12的新特性
codecraft赞 63阅读 12k
Java8的新特性
codecraft赞 32阅读 24.7k评论 1
一文搞懂秒杀系统,欢迎参与开源,提交PR,提高竞争力。早日上岸,升职加薪。
王中阳Go赞 35阅读 2.6k评论 1
Java11的新特性
codecraft赞 28阅读 15.5k评论 3
Java5的新特性
codecraft赞 13阅读 20.5k
Java9的新特性
codecraft赞 20阅读 14.6k
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。