QA:無重複字符的最長子串

無重複字符的最長字串

leetcode地址:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/spa

題目描述:code

給定一個字符串,請你找出其中不含有重複字符的 最長子串 的長度。blog

示例:leetcode

輸入: "abcabcbb"
輸出: 3 

解決思路:字符串

使用map  lastOccured[byte]int 記錄字符和字符最後出現的下標get

對於字符串每一個字符x:string

1.lastOccured[x]不存在 或者 小於start時不作操做。it

2.lastOccured[x]>=start 時,start = lastOccured[x]+1。ast

3.每次都要更新lastOccured[x],更新最大長度maxLength。class

 

代碼以下:

func lengthOfLongestSubstring(s string) int {
    lastOccured := make(map[byte]int)
    start := 0
    maxLength := 0
    for i, ch := range []byte(s){
        if num, ok := lastOccured[ch]; ok&& num >= start{
            start = num + 1
        }
        if i-start+1 > maxLength{
            maxLength = i-start+1
        }
        lastOccured[ch] = i
    }
    return maxLength
}
相關文章
相關標籤/搜索