给你一个字符串 s
和一个字符串数组 dictionary
,找出并返回 dictionary
中最长的字符串,该字符串可以通过删除 s
中的某些字符得到。
如果答案不止一个,返回长度最长且字母序最小的字符串。如果答案不存在,则返回空字符串。
示例 1:
输入:s = "abpcplea", dictionary = ["ale","apple","monkey","plea"] 输出:"apple"
示例 2:
输入:s = "abpcplea", dictionary = ["a","b","c"] 输出:"a"
/**
* @param {string} s
* @param {string[]} dictionary
* @return {string}
*/
var findLongestWord = function(s, dictionary) {
let max = 0,str = ''
for(let i = 0;i<dictionary.length;i++){
let left = 0,right =0
while(left<s.length&&right<dictionary[i].length){
if(s[left]==dictionary[i][right]){
left++
right++
}else{
left++
}
}
if(right>=dictionary[i].length){
if(max<dictionary[i].length||max==dictionary[i].length&&dictionary[i]<str){
max = dictionary[i].length
str = dictionary[i]
}
}
}
return str
};