This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging
The title
Given a string s, find the length of the oldest string (**) that does not contain duplicate characters.
Example 1:
Input: s = “abcabCBb” Output: 3 Explanation: Since the oldest string without repeating characters is “ABC”, its length is 3.
Example 2:
Input: s = “BBBBB” Output: 1 Explanation: Since the oldest string without duplicate characters is “b”, its length is 1.
Example 3:
Input: s = “pwwkew” Output: 3 Explanation: Since the oldest string with no duplicate characters is “wke”, its length is 3. Note that your answer must be the length of the substring, “pwke” is an _ subsequence, _ is not a substring.
Example 4:
Input: s = “” Output: 0
Tip:
0 <= s.length <= 5 * 104
s
It consists of letters, digits, symbols, and Spaces
Their thinking
Idea 1
Double pointer +Set defines an interval, each time you move the starting point or point of the interval. Changes the total Set of character sets currently contained after moving the interval. 1. When the end value is not in the Set, the end of the interval shifts to the right. Arr [start]==arr[end]; arr[end] ==arr[end
/ * * *@param {string} s
* @return {number}* /
var lengthOfLongestSubstring = function(s) {
if(s.length<=1)return s.length
let arr = Array.from(s)
let set = new Set(a)let start=0
let end = 1
let maxLen = 0
set.add(arr[0])
while(start<=end&&start<arr.length&&end<arr.length){
if(! set.has(arr[end])){ maxLen =Math.max(maxLen,end-start)
set.add(arr[end])
end++
}else{
while(start<end){
const result = arr[end]==arr[start]
if(result){
start++
end++
break
}else{
set.delete(arr[start])// Remove the character set from this position after the left and right shift
start++
}
}
}
}
return maxLen+1
};
Copy the code
Idea 2
Execution time: 240 ms, beating 17.47% user memory consumption across all JavaScript commits: 44.1 MB, beating 18.98% user most pull solution across all JavaScript commits
/ * * *@param {string} s
* @return {number}* /
var lengthOfLongestSubstring = function(s) {
if(! s.length)return 0
let res = 1
for(let i = 0; i < s.length; i++){
let a = new Set()
r = i
while(r < s.length&&! a.has(s[r])){ a.add(s[r]) r++ } res =Math.max(res,a.size)
}
return res
};
Copy the code
The last
I dreamed of going all over the world with a sword
Take a look at the prosperity of the world
Young hearts are always a little frivolous
Just a man after all
No regrets I go my way
“Front brush” No.3