Given a string, print the longest substring without repeating characters in Golang. For example, the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA”.
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].
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.
- Length of Longest Palindrome Substring
- Repeating a String for Specific Number of Times in Golang
- Counting number of repeating words in a Golang String
- How to find the length of the pointer in Golang?
- How to find the Length of Channel, Pointer, Slice, String and Map in Golang?
- Check if the given characters is present in Golang String
- How to Replace Characters in Golang String?
- How to Count the Number of Repeated Characters in a Golang String?
- How to count specific characters present in the slice in Golang?
- Golang Program to Find Largest Element in an Array
- Golang program that uses fallthrough keyword
- Golang Program that uses String Switch
- Golang Program that switch on floating-point numbers
- Golang program that uses structs as map keys
- Golang program that uses switch, multiple value cases
- Golang Program to Count Trailing Zeros in Factorial of a Number
- Golang program that uses func with variable argument list
- Golang program that uses func with two arguments
- Program to shift all zero to the end of array in Golang
- Golang program that uses defer keyword