Golang solution (6ms)


  • 0

    Efficient solution (6ms) using an [128] char array limited to the ASCII char set.

    func lengthOfLongestSubstring(s string) int {
        indexMap := [128]int{}
        startIndex, subLen, maxSubLen := 0, 0, 0
        
        for i := 0; i < len(indexMap); i++ { indexMap[i] = -1 }
        for i := 0; i < len(s); i++ {
            indx := indexMap[s[i]]
            if indx >= startIndex {
                subLen = i - indx
                startIndex = indx + 1
            } else {
                subLen++
            }
            indexMap[s[i]] = i
            maxSubLen = max(subLen, maxSubLen)
        }
        return maxSubLen
    }
    
    func max(x, y int) int { if x > y { return x }; return y }
    

    A more generic solution (19ms) using maps is as follows:

    func lengthOfLongestSubstring(s string) int {
        indexMap := make(map[byte]int)
        startIndex, subLen, maxSubLen := 0, 0, 0
    
        for i := 0; i < len(s); i++ {
            indx, exist := indexMap[s[i]]
            if exist && indx >= startIndex {
                subLen = i - indx
                startIndex = indx + 1
            } else {
                subLen++
            }
            indexMap[s[i]] = i
            maxSubLen = max(subLen, maxSubLen)
        }
        return maxSubLen
    }
    
    func max(x, y int) int { if x > y { return x }; return y }
    

Log in to reply
 

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