给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。

    如果答案不止一个,返回长度最长且字母序最小的字符串。如果答案不存在,则返回空字符串。

    示例 1:

    输入:s = “abpcplea”, dictionary = [“ale”,”apple”,”monkey”,”plea”]
    输出:”apple”
    示例 2:

    输入:s = “abpcplea”, dictionary = [“a”,”b”,”c”]
    输出:”a”

    1. /**
    2. * @param {string} s
    3. * @param {string[]} dictionary
    4. * @return {string}
    5. */
    6. var findLongestWord = function (s, dictionary) {
    7. dictionary = dictionary.sort(); // 排序优化速度
    8. let longest = ''; // 存最大值
    9. for (let i = 0; i < dictionary.length; i += 1) {
    10. let curr = dictionary[i]
    11. // 双指针找子序列
    12. let slow = 0, fast = 0;
    13. while (fast < s.length) {
    14. if (curr[slow] === s[fast]) {
    15. slow++
    16. fast++
    17. } else {
    18. fast++
    19. }
    20. }
    21. if (slow === curr.length && curr.length > longest.length) {
    22. longest = curr
    23. }
    24. }
    25. return longest
    26. };

    image.png