Sharing my very concise solution with explanation

  • 1
    int lengthOfLongestSubstring(string s) {
        int map[256] = {0};  //unordered_map<char, int> map;
        int maxLength = 0;
        for(int slow = 0, fast = 0; fast < s.length(); fast++){
            while(map[s[fast]] > 1){
            maxLength = max(maxLength, fast - slow + 1);
        return maxLength;

    The basic idea is to use two pointers to maintain a slide window.

    We increment pointer "fast" in each loop. But when s[fast] is a duplicate element, we should move pointer "slow" forward until s[fast] has no duplicate in hash table. And we should also get maxLength in each loop.

    Finally, return maxLength, which represents the maximum window size.

Log in to reply

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