03.没有重复字符的最长子字符串
给定一个字符串,找出没有重复字符的最长子字符串的长度。
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
解法1:
滑动窗口法,每当字符在当前窗口重复时,调整窗口大小。和最大子数组和看起来有点类似,但是思路不太一样,有机会总结一下区别。
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
let maxLen = 0;
let begin = 0;
let lastIdxOf = {};
for (let i = 0; i < s.length; i ++) {
let char = s.charAt(i);
// if current char repeats in current window, adjust the window
if (lastIdxOf[char] != null) begin = Math.max(begin, lastIdxOf[char] + 1);
if (i - begin + 1 > maxLen) maxLen = i - begin + 1;
lastIdxOf[char] = i;
}
return maxLen;
};