QA: no repeat of the longest character substring

No repeat of the longest string of characters

leetcode Address: https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

Subject description:

Given a string, you find out which does not contain a sub-length of the longest string of repeated characters.

Example:

Enter: "abcabcbb"
Output: 3 

Solutions:

Use map lastOccured [byte] int record last occurrence of the character and the character index

For each character string x:

1.lastOccured [x] does not exist or is not less than the operation start.

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

3. updated every time lastOccured [x], to update the maximum length maxLength.

 

code show as below:

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
}

 

Guess you like

Origin www.cnblogs.com/tulipgirl/p/11829708.html