当前位置: 面试刷题>> 通过删除字母匹配到字典里最长单词 (经典算法题500道)


题目描述补充

题目:给定一个字符串s和一个字符串数组wordDict,其中wordDict包含了一系列单词。你的任务是找到wordDict中可以通过从s中删除某些(或不删除)字符后得到的最长单词。注意,这里的“删除”操作意味着你可以从s中移除任意数量的字符(包括零个),但不可以改变s中剩余字符的顺序。如果有多个最长单词满足条件,则返回其中任意一个即可。如果无法从s中通过删除字符得到wordDict中的任何单词,则返回空字符串。

示例

输入

  • s = "abpcaea"
  • wordDict = ["a", "ab", "abc", "aec", "bp"]

输出: "ab"

解释: "ab" 是 "abpcaea" 的子序列,并且它是 wordDict 中最长的单词。

PHP 示例代码

function findLongestWord($s, $wordDict) {
    $longestWord = '';
    foreach ($wordDict as $word) {
        $i = 0;
        $j = 0;
        while ($i < strlen($s) && $j < strlen($word)) {
            if ($s[$i] === $word[$j]) {
                $j++;
            }
            $i++;
        }
        if ($j === strlen($word) && strlen($word) > strlen($longestWord)) {
            $longestWord = $word;
        }
    }
    return $longestWord;
}

// 示例用法
$s = "abpcaea";
$wordDict = ["a", "ab", "abc", "aec", "bp"];
echo findLongestWord($s, $wordDict); // 输出: ab

Python 示例代码

def findLongestWord(s, wordDict):
    longest_word = ''
    for word in wordDict:
        i, j = 0, 0
        while i < len(s) and j < len(word):
            if s[i] == word[j]:
                j += 1
            i += 1
        if j == len(word) and len(word) > len(longest_word):
            longest_word = word
    return longest_word

# 示例用法
s = "abpcaea"
wordDict = ["a", "ab", "abc", "aec", "bp"]
print(findLongestWord(s, wordDict))  # 输出: ab

JavaScript 示例代码

function findLongestWord(s, wordDict) {
    let longestWord = '';
    for (let word of wordDict) {
        let i = 0, j = 0;
        while (i < s.length && j < word.length) {
            if (s[i] === word[j]) {
                j++;
            }
            i++;
        }
        if (j === word.length && word.length > longestWord.length) {
            longestWord = word;
        }
    }
    return longestWord;
}

// 示例用法
let s = "abpcaea";
let wordDict = ["a", "ab", "abc", "aec", "bp"];
console.log(findLongestWord(s, wordDict)); // 输出: ab

码小课网站中有更多相关内容分享给大家学习,希望这些示例代码和解释能帮助你理解并解答这个问题。