Skip to content

Commit b96ccae

Browse files
committed
Add Sliding window solution for Longest substring
1 parent 99bcd36 commit b96ccae

File tree

1 file changed

+43
-5
lines changed

1 file changed

+43
-5
lines changed

longest_substring.go

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,21 @@ func lengthOfLongestSubstring(s string) int {
1212
for _, v := range s {
1313
vStr := string(v)
1414

15-
// Slower
15+
// Slower (20ms)
1616
// split := strings.Split(current, vStr)
1717
// if len(split) > 1 {
1818
// fmt.Printf("\nFound %s, Resetting %s to: %s", vStr, current, split[1])
1919
// current = split[1]
2020
// }
2121

22-
// Faster
22+
// Faster (12 ms)
2323
oldIndex := strings.Index(current, vStr)
2424
if oldIndex > -1 {
2525
fmt.Printf("\nFound %s at %d, Resetting %s to: %s", vStr, oldIndex, current, current[oldIndex+1:])
2626
current = current[(oldIndex + 1):]
2727
}
2828

29-
current += string(vStr)
29+
current += vStr
3030

3131
if len(current) > len(longest) {
3232
longest = current
@@ -37,9 +37,47 @@ func lengthOfLongestSubstring(s string) int {
3737
return len(longest)
3838
}
3939

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("\nFound %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+
4067
func main() {
41-
test1 := "pwwkew"
42-
test2 := "dvdf"
68+
test1 := "a" // 1
69+
test2 := "bbbbbb" // 1
70+
test3 := "pwwkew" // 3
71+
test4 := "dvdf" // 3
4372
fmt.Printf("\n%d", lengthOfLongestSubstring(test1))
4473
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))
4583
}

0 commit comments

Comments
 (0)