Home » leet code » Leet Code: Longest Substring Without Repeating Characters Java | JavaScript | CPP | Python Solution

Leet Code: Longest Substring Without Repeating Characters Java | JavaScript | CPP | Python Solution

Find the length of the longest substring without repeated characters given a string s.

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.

Solution :

JavaScript :

var lengthOfLongestSubstring = function(s) {
   let max = 0;
   if(s.length === 0) return max; 
   let set =  new Set();

    let p1 = 0;
    let p2 = 0;
    
    while(p2 < s.length) {
        if(!set.has(s[p2])) {
            set.add(s[p2]);
            max = Math.max(max, (p2-p1)+1);
            p2 +=1;
        }
        else{
            set.delete(s[p1]);
            p1 += 1;
        }
    }
    
    return max;
};

Java :

class Solution {
public int lengthOfLongestSubstring(String s) {
    int n= s.length();
    HashMap<Character,Integer> map= new HashMap<>();
    int start=0, end=0;
    int ans=0;
    while(end<n)
    {
        char ch= s.charAt(end);
        map.put(ch,map.getOrDefault(ch,0)+1);
        while(start<end && map.get(ch)>1)
        {
            map.put(s.charAt(start),map.get(s.charAt(start))-1);
            start++;
        }
        ans= Math.max(ans,end-start+1);
        end++;
    }
    return ans;
}   }

CPP :

int lengthOfLongestSubstring(string s) {
    int n=s.length();
    if(n == 0) return 0;
    
    int indx[CHAR];
    fill(indx, indx+CHAR, -1);
    
    int startIndx=0, length = INT_MIN;
    for(int endIndx=0; endIndx<n; endIndx++){
        startIndx = max(startIndx, indx[s[endIndx]]+1);
        length = max(length, endIndx - startIndx + 1);
        indx[s[endIndx]] = endIndx;
    }
    return length;
}

Leave a Reply