Last Commit: 2024-01-06 17:50:27

views:

Table of Content

3. Longest Substring Without Repeating Characters

source: https://leetcode.com/problems/longest-substring-without-repeating-characters/

Question

Given a string s, find the length of the longest substring without repeating characters.

思路

相当经典的一道滑动窗口的题目。在使用滑动窗口的模版的基础上,有一个非常重要的一个判断:window[rightC] > 1。进入循环的初始状态下,肯定是无重复子串的。所以只要当第一个字符串重复,左滑部分肯定对应的也是window[rightC]

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function (s) {
  const window = {};
  let ret = 0;
  let left = 0;
  let right = 0;
  while (right < s.length) {
    const rightC = s[right];
    window[rightC] = (window[rightC] || 0) + 1;
    while (window[rightC] > 1) {
      const leftC = s[left];
      window[leftC]--;
      left++;
    }
    right++;
    ret = Math.max(ret, right - left);
  }
  return ret;
};

End

在使用模版的基础,得有一些小技巧,才可以快速的做出这题。