Problem statement
For a given input string, return length of the longest substring in the given string without repeating characters. Note: the given string includes English letters and digits.
Examples:
Example1:
**Input:** s = "abcabcbb"
**Output: ** 3 (with the substring "abc")
Example 2:
**Input: ** s = "bbbbb"
**Output: ** 1
Example 3:
**Input: ** s = "pwwkew"
**Output: ** 3 (with the substring "kew")
Solution 1: Naive approach
We are using the naive approach by check every possible substring of the given string s and return the length of the longest string without repeating characters. We should follow these steps:
- Generate all possible substrings of s by using two loops
- When you obtain each substring, use a map to check whether there are any repeated character in this substring. If not, compare its length with length of all unique character substrings so far. If the substring has at least repeated characters, skip it.
Code example
func FindLongestSubstring(s string) int { n := len(s) if n == 1 { return 1 } duplicateMap := make(map[string]bool) // to store characters of the substring isDuplicate := false // true is there are any duplicated character in the substring, false if not maxLength := 0 // store length of the longest unique character substring for i := 0; i < n-1; i++ { for j := i; j < n; j++ { duplicateMap = make(map[string]bool) isDuplicate = false for k := i; k <= j; k++ { if _, found := duplicateMap[string(s[k])]; !found { duplicateMap[string(s[k])] = true continue } isDuplicate = true break } if !isDuplicate { maxLength = int(math.Max(float64(maxLength), float64(j-i+1))) } } } return maxLength
}