Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
0 <= s.length <= 5 * 10^4
s consists of English letters, digits, symbols and spaces.
Solution
Approach #0
funclengthOfLongestSubstring(s string) (res int) { sList := []rune(s)for i :=0; i <len(sList); i++ { tmp :=0 m :=make(map[rune]struct{})for j := i; j <len(sList); j++ {if _, ok := m[sList[j]]; ok {break } m[sList[j]] =struct{}{} tmp++ } res =max(res, tmp)delete(m, sList[i]) }return}funcmax(a, b int) int {if a > b {return a }return b}
Approach #1
Approach #1, #2 and #3 shows different process when counting the right side of the window.
funclengthOfLongestSubstring(s string) (res int) { m :=make(map[byte]struct{}) i, j :=0, 0for ; j <len(s); j++ {for ; i < j; i++ {if _, ok := m[s[j]]; !ok {break }delete(m, s[i]) } m[s[j]] =struct{}{} res =max(res, j-i+1) }return}funcmax(a, b int) int {if a > b {return a }return b}
Approach #2
funclengthOfLongestSubstring(s string) (res int) { m :=make(map[byte]struct{}) i, j :=0, 0for j <len(s) { in := s[j] j++if _, ok := m[in]; ok {for i < j { out := s[i] i++if out == in {break }delete(m, out) } } m[in] =struct{}{} res =max(res, j-i) }return}funcmax(a, b int) int {if a > b {return a }return b}
Approach #3
funclengthOfLongestSubstring(s string) (res int) { m :=make(map[byte]int) i :=-1for j :=0; j <len(s); j++ { in := s[j]if last, ok := m[in]; ok { i =max(last, i) } m[in] = j res =max(res, j-i) }return}funcmax(a, b int) int {if a > b {return a }return b}