Leetcode - Sliding Window Maximum
Leetcode - Longest Substring with At Most K Distinct Characters

Leetcode - Longest Substring with At Most Two Distinct Characters

violet posted @ 5 年前 in 算法 with tags Algorithm Golang array , 330 阅读

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/

Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.

Example 2:

Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
func lengthOfLongestSubstringTwoDistinct(s string) int {
    if len(s) == 0 || len(s) == 1 {
        return len(s)
    }
    hash := map[byte]int{}
    first := s[0]
    second := s[0]
    firstIndex := 0
    secondIndex := 0
    i := 0
    j := i + 1
    max := 0
    for j < len(s) {
        first = s[i]
        firstIndex = i
        j = i
         
        for j < len(s) && len(hash) < 3 {
            if _, ok := hash[s[j]]; !ok && len(hash) == 2 {
                break
            }
            if s[j] != first {
                second = s[j]
            }
            if s[j] == first {
                firstIndex = j
            }
            if s[j] == second {
                secondIndex = j
            }
            hash[s[j]]++
            j++
        }
         
        tmp := j - i
        if tmp > max {
            max = tmp
        }
        if firstIndex < secondIndex {
            i = firstIndex + 1
            delete(hash, first)
        } else {
            i = secondIndex + 1
            delete(hash, second)
        }
    }
    return max
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter