3. Longest Substring Without Repeating Characters Leetcode solution in JavaScript (JS)

0

Table of Contents

Problem:

Given a string s, find the length of the longest 

substring without repeating characters.

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.

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

Solution:

This solution uses brute force and time complexity is O(nlogn)

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let fullarray = new Array();
    let maxlength = 0;
    for(let i = 0; i <s.length; i++){
        let temparray = new Array();
        for(let k = i; k <s.length;k++){
            if(temparray.includes(s[k])){
              break;
            }
            temparray.push(s[k]);
        }
        fullarray.push(temparray);
    }
    if(fullarray){
        for(let j =0; j <fullarray.length;j++){
            if(fullarray[j].length > maxlength){
                maxlength = fullarray[j].length;
            }
        }
    }
    return maxlength;
};

Leave a Comment

Skip to content