@@ -12,21 +12,21 @@ func lengthOfLongestSubstring(s string) int {
12
12
for _ , v := range s {
13
13
vStr := string (v )
14
14
15
- // Slower
15
+ // Slower (20ms)
16
16
// split := strings.Split(current, vStr)
17
17
// if len(split) > 1 {
18
18
// fmt.Printf("\nFound %s, Resetting %s to: %s", vStr, current, split[1])
19
19
// current = split[1]
20
20
// }
21
21
22
- // Faster
22
+ // Faster (12 ms)
23
23
oldIndex := strings .Index (current , vStr )
24
24
if oldIndex > - 1 {
25
25
fmt .Printf ("\n Found %s at %d, Resetting %s to: %s" , vStr , oldIndex , current , current [oldIndex + 1 :])
26
26
current = current [(oldIndex + 1 ):]
27
27
}
28
28
29
- current += string ( vStr )
29
+ current += vStr
30
30
31
31
if len (current ) > len (longest ) {
32
32
longest = current
@@ -37,9 +37,47 @@ func lengthOfLongestSubstring(s string) int {
37
37
return len (longest )
38
38
}
39
39
40
+ // Slower (24 ms)
41
+ // Possible explanation here: https://stackoverflow.com/a/29690063/4931825
42
+ // String keys require hashing
43
+ func lengthOfLongestSubstringSlidingWindow (s string ) int {
44
+ soln := 0
45
+ seenMap := map [string ]int {}
46
+ i := 0
47
+
48
+ for j , v := range s {
49
+ vStr := string (v )
50
+
51
+ k , ok := seenMap [vStr ]
52
+ if ok && k >= i {
53
+ i = k + 1
54
+ fmt .Printf ("\n Found %s at %d, Resetting i to: %d, with j == %d" , vStr , k , i , j )
55
+ }
56
+
57
+ seenMap [vStr ] = j
58
+ current := j - i + 1
59
+ if current > soln {
60
+ soln = current
61
+ }
62
+ }
63
+
64
+ return soln
65
+ }
66
+
40
67
func main () {
41
- test1 := "pwwkew"
42
- test2 := "dvdf"
68
+ test1 := "a" // 1
69
+ test2 := "bbbbbb" // 1
70
+ test3 := "pwwkew" // 3
71
+ test4 := "dvdf" // 3
43
72
fmt .Printf ("\n %d" , lengthOfLongestSubstring (test1 ))
44
73
fmt .Printf ("\n %d" , lengthOfLongestSubstring (test2 ))
74
+ fmt .Printf ("\n %d" , lengthOfLongestSubstring (test3 ))
75
+ fmt .Printf ("\n %d" , lengthOfLongestSubstring (test4 ))
76
+
77
+ fmt .Println ("" )
78
+
79
+ fmt .Printf ("\n %d" , lengthOfLongestSubstringSlidingWindow (test1 ))
80
+ fmt .Printf ("\n %d" , lengthOfLongestSubstringSlidingWindow (test2 ))
81
+ fmt .Printf ("\n %d" , lengthOfLongestSubstringSlidingWindow (test3 ))
82
+ fmt .Printf ("\n %d" , lengthOfLongestSubstringSlidingWindow (test4 ))
45
83
}
0 commit comments