Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

无重复字符的最长子串 #6

Open
Bulandent opened this issue Jan 6, 2021 · 0 comments
Open

无重复字符的最长子串 #6

Bulandent opened this issue Jan 6, 2021 · 0 comments

Comments

@Bulandent
Copy link
Owner

Bulandent commented Jan 6, 2021

难度:中等
来源:3. 无重复字符的最长子串

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

示例 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 由英文字母、数字、符号和空格组成

思路:

  • 与其用变量来存储无重复的最长子串,还不如用 max 来存储最长子串的长度,这样内存占用会更小;
  • 最长子串其实就可以看成滑动窗口,子串的左下标 i 就是窗口的左侧位置,子串的右下标 j 就是窗口的右侧位置;
  • 当遍历字符串的时候,就可以通过左坐标 i 来控制窗口左侧位置的移动,而遍历的索引 j 就是右窗口位置;
  • 通过左坐标 i 和遍历索引 j 两个数据即可得到子串,然后将子串和当前字符进行匹配,如果子串包含当前字符则更新左坐标 i,否则更新子串最大长度 max;

题解:滑动窗口

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let max = 0, // 最大长度
        i = 0, // 左下标
        index = 0; // 
    for (let j = 0, l = s.length; j < l; j++) {
        index = s.slice(i, j).indexOf(s[j])
        if (index === -1) {
            max = Math.max(max, j - i + 1)
        } else {
            i += index + 1
        }
    }
    return max
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant