LeetCode3 无重复字符的最长子串

81 阅读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{ // 出现重复字符,需要收缩窗口,left指针前进
            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
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
扩展:如果是要得到该无重复字符最长子串
func main() {
    s1 := "pwwkew"
    fmt.Println(lengthOfLongestSubstring(s1))
}

func lengthOfLongestSubstring(s string) string {
    window := make(map[rune]int) // 记录滑动窗口内字母出现次数
    left, right := 0, 0
    res := ""
    for right < len(s) {
       c := rune(s[right])
       right++
       window[c]++
       for window[c] > 1 { // 出现重复字符,需要收缩窗口,left指针前进
          window[rune(s[left])]-- // 移除窗口左边界的元素
          left++
       }
       if right-left > len(res) {
          res = s[left:right]
       }
    }
    return res
}