LeetCode-The longest substring without repeated characters (js+set data structure)

topic

Given a string, please find out the length of the longest substring that does not contain repeated characters.

Instance

Input: "abcabcbb"
Output: 3
Explanation: Because the longest substring without repeated characters is "abc", its length is 3.
Input: "bbbbb"
Output: 1
Explanation: Because the longest substring without repeated characters is "b", its length is 1.
Input: "pwwkew"
Output: 3
Explanation: Because the longest substring without repeated characters is "wke", its length is 3.
Please note that your answer must be the length of the substring, "pwke" is a subsequence, not a substring.

Ideas

  1. Create a set
  2. Two pointers (don't be scared by this term) The first one points to the beginning of the string j, the second one traverses the string i with the for loop
  3. If there is no s[i] in the set, it means that there are no repeated characters so far. Add s[i] to the set, and then update the maximum number of unique characters.
  4. If there is s[i] in the set, delete s[j] from the set and increment j, then check whether there is s[i] in the set, and repeat until there is no s[i] in the set.
  5. Repeat steps 3 and 4 until the entire string is traversed
const lengthOfLongestSubstring = s => {
    
    
  // 定义两个循环变量和要输出的最大长度的变量
  let i = 0 ,j = 0, maxLength = 0
  const set = new Set()
  //判断数组的长度为0的时候直接返回0
  s.length === 0 && 0 
  
  for(i; i < s.length; i++) {
    
    

    if (!set.has(s[i])) {
    
    
      set.add(s[i])
      maxLength = Math.max(maxLength,set.size)
    }else {
    
    
      while (set.has(s[i])) {
    
    
        set.delete(s[j])  
        j++
      }
      set.add(s[i])
    }
  }
  return maxmaxLength
};

Guess you like

Origin blog.csdn.net/pz1021/article/details/105821543