题目
Given a string, find the length of the longest substring without repeating characters.
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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
- 需要一个可以记录字符串最大值的变量 maxLen
- 实现这个规则结构:
- 不停的往这个结构中输入字符串s中的按序字符
- 若未遇上相同的字符,结构长度累计 maxLen + 1
- 若遇上相同字符,则放弃接近头部相同的字符之前的部分,计入此字符
- 注意边界及何时更新 maxLen
实现
var lengthOfLongestSubstring = function(s) {
let maxLen = 0;
const list = s.split('');
const map = {};
let templist = [];
list.forEach(c => {
if (map[c]) {
let i = templist.length;
while(i) {
if (templist[i - 1] === c) {
const l = templist.splice(0, i);
l.forEach(c => {
map[c] = 0;
})
}
i--;
}
templist.push(c);
map[c] = 1;
} else {
templist.push(c);
map[c] = 1;
maxLen = templist.length > maxLen ? templist.length : maxLen;
}
})
return maxLen;
};