JavaScript学习笔记
题目要求
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
示例 | 输入 & 输出 & 解释 |
---|---|
示例1 | 输入: s = "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3 |
示例2 | 输入: s = "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1 |
示例3 | 输入: s = "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3 请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串 |
示例4 | 输入: s = "" 输出: 0 |
示例5 | 输入:nums1 = [2], nums2 = [] 输出:2.00000 |
– | – |
提示 | 0 <= s.length <= 5 * 104 s 由英文字母、数字、符号和空格组成 |
JavaScript代码
var lengthOfLongestSubstring = function(s) {
if (s.length <= 1) {
return s.length;
}
let maxLength = 0;
let startIndex = 0;
let endIndex = 1;
let theChars = new Map();
theChars.set(s.slice(startIndex, startIndex + 1), startIndex);
while (startIndex != s.length - 1 && endIndex < s.length) {
if (!theChars.has(s.slice(endIndex, endIndex + 1))) {
theChars.set(s.slice(endIndex, endIndex + 1), endIndex);
endIndex += 1;
} else {
if (maxLength < theChars.size) {
maxLength = theChars.size;
}
theChars.clear();
startIndex += 1;
theChars.set(s.slice(startIndex, startIndex + 1), startIndex);
endIndex = startIndex + 1;
}
}
if (theChars.size != 0) {
if (maxLength < theChars.size) {
maxLength = theChars.size;
}
}
return maxLength;
};
解题思路
- 建立一个Map对象theChars,存储无重复的单个字符;
- 以startIndex标定字符串子串起点;
- 以endIndex作为游标遍历,若出现与theChars内相同的字符,则记录当前theChars的size,与maxLength比较;
- 以startIndex += 1为子串起点(待优化),重复上述过程。