一、問題詳情:
給定一個字符串?s
?,請你找出其中不含有重復字符的?最長子串?的長度。
示例?1:
輸入: s = "abcabcbb"
輸出: 3
解釋: 因為無重復字符的最長子串是 "abc"
,所以其長度為 3。
示例 2:
輸入: s = "bbbbb"
輸出: 1
解釋: 因為無重復字符的最長子串是 "b"
,所以其長度為 1。
示例 3:
輸入: s = "pwwkew" 輸出: 3 解釋: 因為無重復字符的最長子串是?"wke"
,所以其長度為 3。請注意,你的答案必須是 子串 的長度,"pwke"
?是一個子序列,不是子串。
二、我的答案:
/*** @param {string} s* @return {number}*/
var lengthOfLongestSubstring = function(s) {let maxLength = 0;let left = 0;const charMap = new Map(); // 用于記錄字符的索引位置for (let right = 0; right < s.length; right++) {const currentChar = s[right];if (charMap.has(currentChar) && charMap.get(currentChar) >= left) {// 如果當前字符已經在窗口中出現過,并且在左指針之后left = charMap.get(currentChar) + 1; // 更新左指針的位置}charMap.set(currentChar, right); // 記錄當前字符的索引位置maxLength = Math.max(maxLength, right - left + 1); // 更新最大長度}return maxLength;
};