LeetCode3 无重复字符的最长子串

38 阅读1分钟

leetcode.cn/problems/lo…

image.png

解法一:滑动窗口

关于滑动窗口的代码框架可以参考该文章:labuladong.online/algo/essent…

func lengthOfLongestSubstring(s string) int {
    window := make(map[rune]int) // 记录滑动窗口内字母出现次数
    left, right := 0, 0
    res := 0
    for right < len(s){
        c := rune(s[right])
        right++
        window[c]++
        for window[c] > 1{
            window[rune(s[left])]--
            left++
        }
        res = max(res, right-left)
    }
    return res
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}