Golang solution example, takes 28ms


  • 0
    func lengthOfLongestSubstring(s string) int {
        start, max := 0, 0
        mp := make(map[rune]int) // key: num, val: index
        for i, c := range(s) {
            if _, ok := mp[c]; ok && mp[c] >= start {
                start = mp[c] + 1
            } else {
                max = intmax(i - start + 1, max)
            }
            mp[c] = i
        }
        return max
    }
    
    func intmax(a, b int) int {
        if a > b {
            return a
        }
        return b
    }
    

    Time complexity: O(N)
    Space complexity: O(N)
    While N is length of s.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.