C++ 12ms 8 lines


  • 0
    int lengthOfLongestSubstring(string s) {
            int ans = 0, freqs[256]; 
            memset(freqs, 0, sizeof(freqs));
            
            for (int l = 0, r = 0, num = 0; r < s.length(); r++) {  // maining a sliding window [l, r]
                if(freqs[s[r]]++ == 1) { num++; }                   // num is the number of repeating chars in window
                if (num > 0 && --freqs[s[l++]] == 1) { num--; }     // window size only increases if contains no repeating chars
                ans = max(ans, r - l + 1);
            }
            
            return ans;
        }
    

Log in to reply
 

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