LeetCode第24天🐱‍🏍

150 阅读1分钟

524. 通过删除字母匹配到字典里最长单词

  • 排序双指针 对字典数组进行倒序排序,localeCompare用本地特定的顺序来比较两个字符串 localeCompare(),这里注意长度相等的小的字符排在前面。
var findLongestWord = function(s, dictionary) {
    dictionary.sort((word1, word2) => {
        if (word1.length !== word2.length) {
            return word2.length - word1.length;
        } else {
            return word1.localeCompare(word2);
        }
    })

    for (let word of dictionary) {
        let i = 0, j = 0
        while (i < word.length && j < s.length) {
            if (word[i] == s[j]) {
                i++
                j++
                if (i == word.length) return word
            }
            else j++
        }
    }

    return ''
};

92. 反转链表 II

0.jpg pre永远指向待反转区域的第一个节点 left 的前一个节点,在循环过程中不变

var reverseBetween = function(head, left, right) {
    // 因为头节点有可能发生变化,使用虚拟头节点可以避免复杂的分类讨论
    const dummy_node = new ListNode(-1);
    dummy_node.next = head;
    let pre = dummy_node;
    for (let i = 0; i < left - 1; ++i) {
        pre = pre.next;
    }

    let cur = pre.next;
    for (let i = 0; i < right - left; ++i) {
        const next = cur.next;
        cur.next = next.next;
        next.next = pre.next;
        pre.next = next;
    }
    return dummy_node.next;
};