0
点赞
收藏
分享

微信扫一扫

【leetcode】词典中最长的单词

eelq 2022-03-18 阅读 55

使用哈希进行求解

//给出一个字符串数组 words 组成的一本英语词典。返回 words 中最长的一个单词,该单词是由 words 词典中其他单词逐步添加一个字母组成。 
//
// 若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。 
//
// 
//
// 示例 1: 
//
// 
//输入:words = ["w","wo","wor","worl", "world"]
//输出:"world"
//解释: 单词"world"可由"w", "wo", "wor", 和 "worl"逐步添加一个字母组成。
// 
//
// 示例 2: 
//
// 
//输入:words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
//输出:"apple"
//解释:"apply" 和 "apple" 都能由词典中的单词组成。但是 "apple" 的字典序小于 "apply" 
// 
//
// 
//
// 提示: 
//
// 
// 1 <= words.length <= 1000 
// 1 <= words[i].length <= 30 
// 所有输入的字符串 words[i] 都只包含小写字母。 
// 
// Related Topics 字典树 数组 哈希表 字符串 排序 👍 268 👎 0


import sun.rmi.runtime.Log;

import java.util.Arrays;
import java.util.HashSet;

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public String longestWord(String[] words) {

        // 按照长度、字典顺序进行排序
        Arrays.sort(words, (a, b) -> {
            if (a.length() != b.length()) {
                return a.length() - b.length();
            } else {
                return b.compareTo(a);
            }
        });

        String longestWord = "";
        HashSet<String> canditates = new HashSet<>();
        canditates.add("");

        // 根据拍好序的字典,逐步匹配当前字符串去掉一位后是否
        // 依旧在map里,如果在就添加,直到判断完所有的字符串,
        // 因为是按字典逆序排序,所以如果存在相同长度的字符串,
        // 则最后会输出按字典顺序较小的那个。
        for (int i = 0; i < words.length; i++) {
            String currentWord = words[i];
            if (canditates.contains(currentWord.substring(0, currentWord.length() - 1))) {
                canditates.add(currentWord);
                longestWord = currentWord;
            }
        }
        return longestWord;
    }
}
//leetcode submit region end(Prohibit modification and deletion)
举报

相关推荐

0 条评论