【Leetcode刷题篇】3.无重复最长子串(JS)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

 

示例 1:

输入: s = "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:

输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:

输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
示例 4:

输入: s = ""
输出: 0
 

提示:

0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成
Given a string s, find the length of the longest substring without repeating characters.

 

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:

Input: s = ""
Output: 0
 

Constraints:

0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.

滑动窗口(可以把它说成毛毛虫算法吗?)

滑动窗口也就是设置多个指针,然后组成一个数组窗口

本题思路:

  • 通过滑动窗口来表示没有重复的子字符串,并且右边窗口的指针即使(遇到使字符串中字符重复的下一个字符)停止了,他还是不会被重新赋值,让左边窗口指针移动,直到窗口中的串没有让右边指针后面的字符重复,右边指针再继续滑动。
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let occ = new Set();
    const length = s.length;
    let count = 0;
    let rightKey = -1, leftKey = 0;
    for( ; leftKey < length; ++leftKey){
        if(leftKey !== 0){
            occ.delete(s[leftKey - 1]);
        }
        for( ; rightKey + 1 < length && !occ.has(s[rightKey + 1]); ++rightKey){
            occ.add(s[rightKey + 1]);
        }
        count = Math.max(count, rightKey - leftKey +1);
    }
    return count;
};

队列实现滑动窗口(毛毛虫算法 = w =)

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    var res = 0,
        i = 0;
    var temp = [];
    while(i < s.length) {
        console.log("indexOf " + temp.indexOf(s[i]));
        if(temp.indexOf(s[i]) === -1) {
            temp.push(s[i]);
            console.log("push " + temp);
        } else {
            temp.shift();
            console.log("shift " + temp);
            continue;
        }
        res = Math.max(res, temp.length);
        i++;
    }
    return res;
};

console.log(lengthOfLongestSubstring(“pwwkew”));
后:
在这里插入图片描述

posted @ 2020-12-12 15:37  嗨Sirius  阅读(181)  评论(0编辑  收藏  举报