Skip to content

Commit 4ff94a7

Browse files
committed
无重复字符的最长子串
1 parent 853e330 commit 4ff94a7

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

leet_code/lengthOfLongestSubstring_test.go

+15-10
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,23 @@ import (
55
)
66

77
func TestLengthOfLongestSubstring(t *testing.T) {
8-
t.Log(lengthOfLongestSubstring("abcabcbb"))
9-
}
10-
11-
type Data struct {
12-
Index int
13-
Val int
14-
have bool
8+
t.Log(lengthOfLongestSubstring("abcdefgafkzwb"))
159
}
1610

1711
func lengthOfLongestSubstring(s string) int {
18-
if len(s) == 0 {
19-
return 0
12+
lastOccurred := make(map[byte]int)
13+
start := 0
14+
maxLength := 0
15+
for i, ch := range []byte(s) {
16+
//找到上次该字母出现的起点
17+
//判断该位置是否大于起点
18+
if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
19+
start = lastI + 1 //从该字母后一位作为起点,以前的存在相同的而且已经判断就不再判断
20+
}
21+
if i-start+1 > maxLength {
22+
maxLength = i - start + 1
23+
}
24+
lastOccurred[ch] = i
2025
}
21-
return 0
26+
return maxLength
2227
}

0 commit comments

Comments
 (0)