Leetcode 3. Longest Substring Without Repeating Characters

twisted-fate發表於2019-05-23

這題用滑動視窗花了好久啊 , 可能晚上有點分心吧 , 差點就絕望了 , 主要是縮小視窗的時候沒有維護好 left 指標和 map , 寫虛擬碼的時候就寫錯了 ,
覆盤結果 : 下次寫完虛擬碼直接用虛擬碼走幾個能覆蓋大部分情況的測試用例

Leetcode 3. Longest Substring Without Repeating Characters

Leetcode 3. Longest Substring Without Repeating Characters

第一版將就下...至少比之前暴力破解快多了

Leetcode 3. Longest Substring Without Repeating Characters

Leetcode 3. Longest Substring Without Repeating Characters


func lengthOfLongestSubstring(s string) int {
    max:=0
    j:=0
    k:=-1
    curWmap:=make(map[uint8]int)
    curWsize:=0
    endIndex:=len(s)-1

    for ;k<endIndex; {
        k++
        if _,ok:=curWmap[s[k]];!ok{
            curWmap[s[k]]= k
            curWsize++
            max=maxC(curWsize,max)
        } else {
            curWsize++
            orij:=j
            j=curWmap[s[k]]+1
            curWsize=curWsize-(j-orij)
            for ;orij<j;orij++ {
                delete(curWmap,s[orij])
            }
            curWmap[s[k]]=k
            //sub:=curWmap[s[k]]
            //curWsize=curWsize - (sub-j)
            //orij:=j
            //curWmap[s[k]] = j
            //j=sub+1
            //
        }
    }
    return max

}

func maxC(l int,r int) int{
    if l>r {
        return l
    }
    return r
}

bobo sir的解 , 寫虛擬碼走一遍他的思路

Leetcode 3. Longest Substring Without Repeating Characters

虛擬碼嘗試走邏輯

if  window next not overflow  and window next is not in map
    r++
    put s[r] into map  

else
    window left step forward and remove from map (warn that r is not move ) , which is says that move left until no duplicate with s[r+1]

then calculate the window size by left , right pointer ,  find out the max size with currentMax
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章