3.无重复的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串的长度。
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
这题看到最长子串就可以思考是否能够使用滑动窗口来解题了,实际上这题也就是使用滑动窗口来解题。
思路:我们使用两个指针,start 和 end,end 先移动,并且每移动一步,就将对应的字符存入到 map 中,然后使用 map 来判断字符是否已经出现过了,如果已经出现过了,此时 end 停止移动,然后 start 开始移动,移动到字符消失之后,我们计算 end-start ,然后和 res 比较,将 res 的值更新,最后返回 res 的值即可。
图解:
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
// 这题看到题目,就应该要想到使用滑动窗口来解题
let start = 0
let end = 0
// 用来存储最后要返回的最大值
let res = 0
// 我们使用一个 map 表来存储字符,使用 map 的相关 api 来判断和操作窗口的移动
let map = new Map()
while(end < s.length) {
let c = s[end]
end++
// 将值存入
map.set(c, (map.get(c) || 0) + 1)
while(map.get(c) > 1) {
let d = s[start]
start++
map.set(d, map.get(d) - 1)
}
res = Math.max(res, end - start)
}
return res
};