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

 

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

 

 


题目标签:Hash Table

  题目给了我们一个 words array,让我们找到里面 最长的word,这个word 是由字典里的其他words 由短到长一步步形成。如果遇到两个同样长度的单词,选一个 字母排序靠前的。

  这道题目如果用常规方法做,会比较繁琐,速度也慢。

 

  可以利用sort words,让所有words排序。

  遍历words,遇到长度等于 1的 word 或者 这个word 去掉最后一个char 已经存在于 set:

    与res 比较 留下 较长的;

    把这个word 加入set。

 

  因为是排序后的words,所以遍历顺序会是从a 到z, 从短到长。这样就会留下 最长的符合标准的word。也不用考虑 两个同样长度的 words,因为先选的就是 字母排序靠前的。

 

 

 

Java Solution:

Runtime beats 71.19% 

完成日期:11/16/2017

关键词:HashSet,sort

关键点:把word 长度为1 的基础单词 加入 set

 1 class Solution 
 2 {
 3     public String longestWord(String[] words) 
 4     {
 5         Arrays.sort(words);
 6         
 7         Set<String> set = new HashSet<>();
 8         String res = "";
 9         
10         for(String word: words)
11         {
12             if(word.length() == 1 || set.contains(word.substring(0, word.length() - 1)))
13             {
14                 res = word.length() > res.length() ? word : res; // keep the longer one
15                 set.add(word);
16             }
17                 
18         }
19         
20         return res;
21     }
22 }

参考资料:

https://discuss.leetcode.com/topic/109643/java-c-clean-code

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2017-11-17 06:00  Jimmy_Cheng  阅读(818)  评论(0编辑  收藏  举报