https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/?envType=study-plan-v2&envId=top-interview-150

 

 

package leetcode150

import "testing"

func TestLengthOfLongestSubstring(t *testing.T) {
    s := "au"
    res := lengthOfLongestSubstring(s)
    println(res)
}

func lengthOfLongestSubstring(s string) int {
    cMap := make(map[byte]int)
    left, right, maxLen := 0, 0, 0
    for right < len(s) {
        c := s[right]
        if cMap[c] == 1 {
            if maxLen < right-left {
                maxLen = right - left
            }
            for ; left <= right && s[left] != c; left++ {
                delete(cMap, s[left])
            }
            left++
            right++
        } else if right == len(s)-1 {
            if maxLen < right-left+1 {
                maxLen = right - left + 1
            }
            break
        } else {
            cMap[c]++
            right++
        }
    }
    return maxLen
}