top of page

3. Longest Substring Without Repeating Characters

Overall

Introduction

Longest Substring Without Repeating Characters is a first a string and substring problem in Leetcode.

​

This problem require the program find a substring length which is longest substring with the substring must not have any repeat character(e.g. The string cannot include more than two "A", "ABA" is ineligible).

For example, the longest substring in string "abcabcbb" is "abc" which has not any repeating characters. The length of this substring is 3.

​

Problem Content

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.

Concept

The problem is provide a string called "s" then the program need to return a length which is longest cubstring without repeating characters.

First, we let integer "Longest_Length" to save a longest record and "len" for a length of whole "s". And use "start" as the start index of substring and "end" as the end index of substring.

Next, we use while loop for checking with the condition is "end<len" make the checking will end after the end index is go to last index of "s".

​

Then use "if(substring.includes(s[end]))" to check if the substring contains a character which will be added to the substring or not. If the substring is include that character, the "start" will +1 to make start index move forward until the substring is not include that character.


After that we will use "Math.max(Longest_Length,substring.length)" to compare "Longest_Length" with the length of the substring, Longest_Length" will be replace if the length is longer than "Longest_Length".

​

Finally the program return "Longest_Length" after above while loop checking.

Solve(Javascript)

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let Longest_Length=0;
    let len=s.length;
    let start=0;
    let end=0;
    let substring=[];
    
    while(end<len){
        if(substring.includes(s[end])){
           substring.shift();
            start+=1;
           }else{
               substring.push(s[end]);
               end+=1;      
           }
        Longest_Length=Math.max(Longest_Length,substring.length);   
          }
    
    return Longest_Length;
};

bottom of page