【两次过】Lintcode 1071. 词典中最长的单词

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/82893674

给出一系列字符串单词表示一个英语词典,找到字典中最长的单词,这些单词可以通过字典中的其他单词每次增加一个字母构成。 如果有多个可能的答案,则返回字典顺序最小的那个。

如果没有答案,则返回空字符串。

样例

样例1:

输入: 
words = ["w","wo","wor","worl", "world"]
输出: "world"
解释: 
单词"world" 可以通过 "w", "wo", "wor", and "worl"每次增加一个字母构成。

样例2:

输入: 
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
输出: "apple"
解释: 
单词"apply" 和 "apple" 都能够通过字典里的其他单词构成。 但是 "apple" 的字典序比 “apply”小。

注意事项

  1. 输入中的所有字符串只包含小写字母。
  2. words 的长度范围为 [1, 1000].
  3. words[i] 的长度范围为 [1, 30].

解题思路:

先对数组进行排序,然后从最长单词即右边开始遍历,找到满足条件的单词则装入TreeSet中,最后返回treeSet中最小的元素即可。

需满足的条件有两个:1、最长的单词 2、每个单词的字串都在数组中

public class Solution {
    /**
     * @param words: a list of strings
     * @return: the longest word in words that can be built one character at a time by other words in words
     */
    public String longestWord(String[] words) {
        // Write your code here
        //存储单词,便于后面查找
        HashSet<String> set = new HashSet<>();
        for(String word : words)
            set.add(word);
        
        //排序,这样就能从最长的单词开始查找
        Arrays.sort(words);
        //存储所有满足题目条件的单词
        TreeSet<String> treeSet = new TreeSet<>();
        //满足题目条件单词的最大长度,用这个条件将中间字符筛选掉,比如“a”,"ap"等等之类的
        int maxLength = 0;
        
        //从后向前查找,将满足条件的单词存入treeSet中
        for(int i=words.length-1 ; i>=0 ; i--){
            boolean flag = true;
            for(int j=1 ; j<words[i].length() ; j++){
                //若任一子串不在数组中,则不满足条件
                if(!set.contains(words[i].substring(0,j))){
                    flag = false;
                    break;
                }
            }
            //任一字串都在数组中,且是最长的单词,满足条件
            if(flag){
                maxLength = Math.max(words[i].length(),maxLength);
                if(words[i].length() == maxLength)
                    treeSet.add(words[i]);
            }
        }
        
        if(treeSet.isEmpty())
            return "";
        else
            return treeSet.first();
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/82893674