LeetCode: Longest Substring Without Repeating Characters Posted on January 26, 2018July 26, 2020 by braindenny Longest Substring Without Repeating Characters Similar Problems: LeetCode: Substring with Concatenation of All Words CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #slidingwindow, #atmostkdistinct Given a string, find the length of the longest substring without repeating characters. Examples: Given “abcabcbb”, the answer is “abc”, which the length is 3. Given “bbbbb”, the answer is “b”, with the length of 1. Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring. Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. // https://code.dennyzhang.com/longest-substring-without-repeating-characters // Basic Ideas: Sliding window // // Complexity: Time O(n), Space O(1) func lengthOfLongestSubstring(s string) int { l := make([]int, 128) res := 0 // s[i...j] i := 0 for j, v := range s { index := byte(v) l[index]++ for l[index] > 1 { l[s[i]]-- i++ } if j-i+1 > res { res = j-i+1 } } return res } // https://code.dennyzhang.com/longest-substring-without-repeating-characters // Basic Ideas: Sliding window // // Complexity: Time O(n), Space O(n) func lengthOfLongestSubstring(s string) int { m := map[byte]int{} res := 0 // s[i...j] i := 0 for j, _ := range s { v := byte(s[j]) m[v]++ for m[v]>1 { m[s[i]]-- i++ } if j-i+1 > res { res = j-i+1 } } return res } Post Views: 3