【leetcode】词典中最长的单词

使用哈希进行求解

//给出一个字符串数组 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值