题目
给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。
示例
输入:s = “abpcplea”, dictionary = [“ale”,“apple”,“monkey”,“plea”]
输出:“apple”
输入:s = “abpcplea”, dictionary = [“a”,“b”,“c”]
输出:“a”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
想法
1、先将dictionary按照 长度由长到短,字典序由小到大排序
dictionary.sort(key=lambda x:(-len(x),x))
2、双指针遍历匹配字符
3、输出最大的
实现
方法1:python
class Solution:
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
res=list()
dictionary.sort(key=lambda x:(-len(x),x))
for i in range(len(dictionary)):
var=0
k=0
j=0
while(k<len(s) and j<len(dictionary[i])):
if dictionary[i][j]==s[k]:
k+=1
j+=1
var+=1
else:
k+=1
if var==len(dictionary[i]):
res.append(var)
else:
res.append(0)
flagv=max(res)
for i,v in enumerate(res):
if v==flagv:
flag=i
break
if flagv==0:
return("")
else:
return(dictionary[flag])
方法2:java
class Solution {
public String findLongestWord(String s, List<String> dictionary) {
String res = "";
for (String str : dictionary) {
// 如果dictionary的元素是s的字串
if (isSubsequence(str, s)) {
// 如果长度大于直接copy
if (str.length() > res.length()) {
res = str;
} else if (str.length() == res.length()) {
// 相等则比较字典序
if (str.compareTo(res) < 0) {
res = str;
}
}
}
}
return res;
}
public boolean isSubsequence(String s, String t) {
if (s.length() == 0) {
return true;
}
// 记录下标
int cnt_s = 0, cnt_t = 0;
// 逐位比较
while (cnt_t < t.length()) {
if (s.charAt(cnt_s) == t.charAt(cnt_t)) {
cnt_s++;
}
cnt_t++;
// s是t的字串
if (cnt_s == s.length()) {
return true;
}
}
return false;
}
}