LeetCode 算法题【Medium】:3. Longest Substring Without Repeating Characters

链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/

Question

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

Example 1:

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

Example 2:

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

Example 3:

1
2
3
4
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.

My Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var lengthOfLongestSubstring = function(s) {
const strArr = s.split('')
const arrLen = strArr.length
const letterCnt = new Set(strArr).size
if (letterCnt === 1) return 1
if (letterCnt === arrLen) return s.length
for(let strLen = letterCnt; strLen > 0; strLen--) {
for (let startIdx = 0; startIdx <= arrLen - strLen; startIdx ++) {
const str = s.slice(startIdx, startIdx + strLen)
const arr = str.split('')
if (arr.length === new Set(arr).size) {
return str.length
}
}
}
return result.length
};