Given a string, find the length of the longest substring without repeating characters.
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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.
constlengthOfLongestSubstring = (s) => { let i = 0; let maxLen = 0; let left = 0; // 当前子串的左侧位置 const map = {}; while (i < s.length) { const letter = s[i]; const repeat = map[letter]; if (repeat >= 0 && repeat >= left) { if (i - left >= maxLen) { maxLen = i - left; } // 有重复, 重置左侧位置 left = repeat + 1 } map[letter] = i i += 1; } // 最后一位为不重复子串, 且当前的不重复子串 > maxLen if (s.length - left > maxLen) { maxLen = s.length - left; } return maxLen; };
constlengthOfLongestSubstring = (s) => { let i = 0; let maxLen = 0; let left = 0; const map = newMap(); while (i < s.length) { const letter = s[i]; const repeat = map.get(letter); if (repeat >= 0 && repeat >= left) { if (i - left >= maxLen) { maxLen = i - left; } left = repeat + 1 } map.set(letter, i); i += 1; } if (s.length - left > maxLen) { maxLen = s.length - left; } return maxLen; };