524. 通过删除字母匹配到字典里最长单词
给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。
思路:
现将列表中元素按从大到小的顺序排序,对于长度相同的,按照字典序排序
再使用双指针判断当前元素能否通过s删除部分字符得到。
class Solution {
public String findLongestWord(String s, List<String> dictionary) {
// 将列表中的字符串按照长度从大到小进行排序
// 双指针判断s是否包含当前字符串,若包含,则直接返回,否则继续遍历
Collections.sort(dictionary, (a, b) -> {
if (a.length() == b.length()) {
return a.compareTo(b);
}
return b.length() - a.length();
});
for(String current_str:dictionary) {
int first=0,second=0;
while(first<s.length()&&second<current_str.length()) {
if (s.charAt(first)==current_str.charAt(second)) {
first++;
second++;
}
else
first++;
}
if (second!=current_str.length()&&first==s.length())
continue;
else
return current_str;
}
return "";
}
}