In this article, We are going to learn to find the length of the longest substring without repeating characters in go golang.
Example_1:
Input: "abcabcbb"
Output: 3
Explanation: Answer is “abc” which has length of 3
Example_2:
Input: “bbbb”
Output: 1
Explanation: Answer is “b” which has length of 1
Example_3:
Input: "pwwkew"
Output: 3
Explanation : Answer is “wke” which has length of 3
Note: Answer must be substring. Here, "pwke" is a subsequence and not a substring.
Algorithm:
Steps are given below to find the length of the longest substring without repeating characters:
- Get the string as input from user
- Get the length of string
- create an array which will use character ascii value as index number.
- Start searching non-repeating character in a sequence in string. If there is unique character then increment count by 1 and set array index (character ascii value) as true.
- If there is any repeating character then break the loop.
- Compare count with max value. if count is greater than max value. Then assign count value to max variable.
Code:
package main
import (
"fmt"
)
func lengthOfLongestSubstring(str string) {
str_len := len(str)
arr := make([]bool, 125)
max := 1
count := 0
// If string length is zero
if str_len == 0 {
max = 0
} else {
for i := 0; i < str_len; i++ {
for j := 0; j < 125; j++ {
arr[j] = false
}
count = 0
arr[str[i]] = true
count = 1
for k := i + 1; k < str_len; k++ {
if arr[str[k]] {
break
}
arr[str[k]] = true
count = count + 1
if max < count {
max = count
}
}
}
}
fmt.Println(max)
}
func main() {
var str string
// Get input string from user
fmt.Print("Enter string: ")
fmt.Scan(&str)
lengthOfLongestSubstring(str)
}
Output:
Enter string: abcabcbb
3
Enter string: bbbbb
1
Enter string: pwwkew
3
To learn more about golang, Please refer given below link:
https://www.techieindoor.com/go-lang-tutorial/
References:
https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println