友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
|
|
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

公众号的微信号是: jikerizhi。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
524. 通过删除字母匹配到字典里最长单词
给你一个字符串 s 和一个字符串数组 dictionary,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字母序最小的字符串。如果答案不存在,则返回空字符串。
示例 1:
输入:s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] 输出:"apple"
示例 2:
输入:s = "abpcplea", dictionary = ["a","b","c"] 输出:"a"
提示:
-
1 <= s.length <= 1000 -
1 <= dictionary.length <= 1000 -
1 <= dictionary[i].length <= 1000 -
s和dictionary[i]仅由小写英文字母组成
思路分析
可以先对字段做排序,然后从前向后查找符合要求的单词。
也可以直接查找,跳过不符合要求的字符串。
-
一刷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2026-02-25 20:34:08
*/
public String findLongestWord(String s, List<String> dictionary) {
dictionary.sort(Comparator
.comparingInt(String::length)
.reversed()
.thenComparing(Comparator.naturalOrder()));
char[] chars = s.toCharArray();
for (String d : dictionary) {
if (isSequence(d.toCharArray(), chars)) {
return d;
}
}
return "";
}
private boolean isSequence(char[] sub, char[] chars) {
int i = 0;
for (char c : chars) {
if (sub[i] == c && ++i == sub.length) {
return true;
}
}
return false;
}

