How to find longest substring without repeating characters in a given string ?

2.12K viewsProgrammingalgorithm javascript longest substring
0

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.
Answered question
0

This problem follows a sliding window mechanism and can be easily solved by looping through the characters using indexes sliding over them

Javascript code below

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let windowStart = 0,
    maxLength = 0,
    charIndexMap = {};
         for (let windowEnd = 0; windowEnd < s.length; windowEnd++) {
     if (typeof charIndexMap[s[windowEnd]] !== 'undefined') {
      windowStart = Math.max(windowStart, charIndexMap[s[windowEnd]]+1);
    }
             charIndexMap[s[windowEnd]] = windowEnd;
    maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
     }
     return maxLength;
};

Answered question
You are viewing 1 out of 1 answers, click here to view all answers.
Write your answer.

Categories