forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest_substring.go
91 lines (71 loc) · 2.09 KB
/
longest_substring.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"fmt"
"math"
)
// Find takes a slice and looks for an element in it. If found it will
// return true otherwise it will return false.
func Find(slice []string, val string) (int, bool) {
for i := 0; i < len(slice); i++ {
if string(slice[i]) == val {
return i, true
}
}
return -1, false
}
func longestSubstring(value string) {
if len(value) == 0 {
fmt.Println("String is empty")
} else {
left := 0
right := 0
maxLength := 0 // max lenght of substring
var uniqueChars []string // to store the visited chars.
var start int // starting index for longest substring with non repeating char.
var end int // ending index for longest substring with non repeating char.
for right < len(value) && left < len(value) {
index, isThere := Find(uniqueChars, string(value[right]))
if !isThere {
uniqueChars = append(uniqueChars, string(value[right]))
maxLength = int(math.Max(float64(maxLength), float64(len(uniqueChars))))
if maxLength == len(uniqueChars) {
// if the maxLenght == lenght of uniqeChars it might be the longest substring
// with non repeating char.
// si it's stroing the starting and ending index of that substring
start = left
end = right
}
right++
} else {
char := string(value[left])
// finding the index of char that is repeatating in substring
index, isThere = Find(uniqueChars, char)
if isThere {
// this simple removes the that char from this slice
uniqueChars = append(uniqueChars[:index], uniqueChars[index+1:]...)
left++
}
}
}
fmt.Print("Longest Substring Without Repeating Characters: ")
fmt.Println(value[start : end+1])
}
}
func main() {
var input string
fmt.Println("enter the string without space")
fmt.Scanf("%s", &input)
longestSubstring(input)
}
/*
input/output sample
enter the string without space
pwwkew
Longest Substring Without Repeating Characters: kew
enter the string without space
bbbbb
Longest Substring Without Repeating Characters: b
enter the string without space
abcabcbb
Longest Substring Without Repeating Characters: abc
*/