LeetCode Hot 100 (滑动窗口)

93 阅读1分钟

滑动窗口

无重复字符的最长子串

思路

利用滑动窗口:

用字符串 queue 代表滑动窗口里的子串内容,max 代表满足条件的最长子串长度。

  1. 初始化max = 0, queue = ""

  2. 遍历字符串

    • 若当前字符(值)不在滑动窗口中,则直接将其加入滑动窗口(扩大滑动窗口)
    • 若当前字符(值)在滑动窗口中,则更新 max,然后将滑动窗口中的该字符(值)及其左侧所有字符去除,最后,将当前字符加入滑动窗口
  3. 返回值Math.max(max, queue.length)

    无重复字符的最长子串.png

代码

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function (s) {
    let max = 0, queue = ""
    for (let i = 0; i < s.length; i++) {
        let index = queue.indexOf(s[i])
        if (index !== -1) {
            max = Math.max(max, queue.length)
            queue = queue.slice(index + 1)
        }
        queue += s[i]
    }
    
    return Math.max(max, queue.length)
};

找到字符串中所有字母异位词

思路

找到字符串中所有字母异位词.png

代码

/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
var findAnagrams = function (s, p) {
    let slen = s.length
    let plen = p.length
    if (slen < plen)
        return []
    
    let res = []
    let pcnt = new Array(26).fill(0)
    let scnt = new Array(26).fill(0)
    
    for (let i = 0; i < plen; i++) {
        pcnt[p[i].charCodeAt() - 'a'.charCodeAt()]++
        scnt[s[i].charCodeAt() - 'a'.charCodeAt()]++
    }
    if (scnt.toString() == pcnt.toString())
        res.push(0)
    
    for (let i = 0; i < slen - plen; i++) {
        scnt[s[i].charCodeAt() - 'a'.charCodeAt()]--
        scnt[s[i + plen].charCodeAt() - 'a'.charCodeAt()]++
        if (scnt.toString() == pcnt.toString())
            res.push(i + 1)
    }
    
    return res
};