这是 LeetCode 上 2021-9-14 的每日一题:「524. 通过删除字母匹配到字典里最长单词」
1. 题目描述
给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。
示例1:
输入:s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
输出:"apple"
示例2:
输入:s = "abpcplea", dictionary = ["a","b","c"]
输出:"a"
2. 解答
- 按照字符串长度降序、字典序先将字典排序
- 在字典中逐个检验字符串是否满足条件
- 检验时,用双指针遍历来判断
const findLongestWord = (s, dictionary) => {
// 按照字符串长度降序、字典序排序
dictionary.sort((a, b) => (a.length === b.length ? a.localeCompare(b) : b.length - a.length));
const lenS = s.length;
for (const word of dictionary) {
// 两个指针
let [S, W] = [0, 0];
const lenW = word.length;
while (S < lenS && W < lenW) {
if (s[S] === word[W]) W++;
S++;
}
// W指针走到头说明word匹配完成
if (W === lenW) return word;
}
return '';
};
😄最近新创建了个开源仓库,总结 LeetCode 的每日一题,目前已有 C++、JavaScript 语言版本,欢迎大家提供其他语言版本!
🖥️仓库地址:「每日一题系列」