-
Notifications
You must be signed in to change notification settings - Fork 376
/
no_repeat_substring_test.go
75 lines (60 loc) · 1.42 KB
/
no_repeat_substring_test.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
Problem:
- Given a string, find the length of the longest substring which has no repeating characters.
Example:
- Input: "aabccbb"
Output: 3
Explanation: Longest substring which has no repeating characters.is "abc"
Approach:
- Similar to longest substring with k distinct characters, we can use a hashmap
to remember the last index of each character we have processed.
Cost:
- O(n) time, O(k) space where k is the number of characters in the map.
*/
package gtci
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestNoRepeatSubstring(t *testing.T) {
tests := []struct {
in string
expected int
}{
{"", 0},
{"a", 1},
{"aa", 1},
{"ab", 2},
{"aba", 2},
{"abba", 2},
{"abb", 2},
{"abc", 3},
{"abccde", 3},
{"aabccbb", 3},
}
for _, tt := range tests {
common.Equal(
t,
tt.expected,
noRepeatSubstring(tt.in),
)
}
}
func noRepeatSubstring(s string) int {
maxLength, start := 0, 0
// char remembers the last index of each character we have processed.
char := map[string]int{}
for end := range s {
endChar := string(s[end])
// if we have seen the character before, update the start index to
// skip visited characters.
if _, ok := char[endChar]; ok {
start = common.Max(start, char[endChar]+1)
}
// cache the current character' index.
char[endChar] = end
// update the maximum length.
maxLength = common.Max(maxLength, end-start+1)
}
return maxLength
}