Simple 6 lines C++ solution using two pointers approach


  • 0
    T

    We use two pointers left and right to keep track the substring without repeating characters. The left pointer moves by 1 step each time. For each position of the left, we extend the right pointer to as far as we can and update the max if r-l is greater than the max.

        int lengthOfLongestSubstring(string s) {
            int count[256] = {0}, ans = 0, n = s.length();
            for(int l = 0, r = 0; l < n && r < n; count[s[l++]]--){
                while (r < n && count[s[r]] == 0)  count[s[r++]]++;
                if (r-l > ans) ans = r-l;
            }
            return ans;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.