/**
* 通过删除字母匹配到字典里最长单词
* @param {String} s 输入字符串
* @param {Array} dictionary 输入字符串数组
* @return {String} str 输出
*/
let s = "abpcplea",
dictionary = ["ale", "apple", "monkey", "plea"];
let s1 = "abpcplea",
dictionary1 = ["a", "b", "c"];
var findLongestWord = function (s, dictionary) {
let str = ''
let left = 0
let right = 0
for (let i = 0; i < dictionary.length; i++) {
left = 0
right = 0
// console.log(dictionary[i].length)
while(left<s.length&&right<dictionary[i].length){
if (s[left] == dictionary[i][right]) {
++right
}
if (dictionary[i].length == right) {
if (dictionary[i].length > str.length || (dictionary[i].length == str.length&&dictionary[i]<str)) {
str = dictionary[i]
}
}
++left
}
}
return str
// console.log(str)
};
console.log(findLongestWord(s,dictionary))
console.log(findLongestWord(s1,dictionary1))
//apple a
13.手写JavaScript通过删除字母匹配到字典里最长单词
于 2024-04-20 19:54:54 首次发布