-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubstring.go
More file actions
36 lines (33 loc) · 1.01 KB
/
substring.go
File metadata and controls
36 lines (33 loc) · 1.01 KB
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
package main
import "fmt"
//A function which returns the length of longest substring.
//Which takes a String as input.
func SubString(inputString string) int {
if len(inputString) == 0 {
return 0
}
charLastIndex := map[rune]int{}
currentSubStringLength, longestSubStringLength, start := 0, 0, 0
for index, character := range inputString {
if lastIndex, hasCharacter := charLastIndex[character]; !hasCharacter || lastIndex < index-currentSubStringLength {
currentSubStringLength++
} else {
if currentSubStringLength > longestSubStringLength {
longestSubStringLength = currentSubStringLength
}
start = lastIndex + 1
currentSubStringLength = index - start + 1
}
charLastIndex[character] = index
}
if currentSubStringLength > longestSubStringLength {
longestSubStringLength = currentSubStringLength
}
return longestSubStringLength
}
func main() {
fmt.Println(SubString("abcabcbb"))
fmt.Println(SubString("bbbbb"))
fmt.Println(SubString("pwwkew"))
fmt.Println(SubString("javaconceptoftheday"))
}