Program to find the Length of the longest substring without repeating characters in Golang
Last Updated :
10 May, 2020
Given a string, print the longest substring without repeating characters in Golang. For example, the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA”.
Examples:
Input : GEEKSFORGEEKS
Output :
Substring: EKSFORG
Length: 7
Input : ABDEFGABEF
Output :
Substring: BDEFGA
Length: 6
The idea is to traverse the string and for each already visited character store its last occurrence in an array pos of integers(we will update the indexes in the array based on the ASCII values of the characters of the string). The variable st stores starting point of current substring, maxlen stores length of maximum length substring, and start stores starting index of maximum length substring.
While traversing the string, check whether the current character is already present in the string by checking out the array pos. If it is not present, then store the current character’s index in the array with value as the current index. If it is already present in the array, this means the current character could repeat in the current substring. For this, check if the previous occurrence of character is before or after the starting point st of the current substring. If it is before st, then only update the value in array. If it is after st, then find the length of current substring currlen as i-st, where i is current index.
Compare currlen with maxlen. If maxlen is less than currlen, then update maxlen as currlen and start as st. After complete traversal of string, the required longest substring without repeating characters is from s[start] to s[start+maxlen-1].
package main
import "fmt"
func longest_substring(s string, n int ) string {
var i int
st := 0
currlen := 0
maxlen := 0
start := 0
pos := make([] int , 125)
for i = 0; i < 125; i++ {
pos[i] = -1
}
pos[s[0]] = 0
for i = 1; i < n; i++ {
if pos[s[i]] == -1 {
pos[s[i]] = i
} else {
if pos[s[i]] >= st {
currlen = i - st
if maxlen < currlen {
maxlen = currlen
start = st
}
st = pos[s[i]] + 1
}
pos[s[i]] = i
}
}
if maxlen < i-st {
maxlen = i - st
start = st
}
ans := ""
for i = start; i < start+maxlen; i++ {
ans += string(s[i])
}
return ans
}
func main() {
var s string = "GEEKSFORGEEKS"
var n int = len(s)
var newString = longest_substring(s, n)
var length int = len(newString)
fmt.Println( "Longest substring is: " , newString)
fmt.Println( "Length of the string: " , length)
}
|
Output:
Longest substring is: EKSFORG
Length of the string: 7
Note: Instead of using the array, we can also use a map of string to int.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...