0003._Longest_Substring_without_Repeating_Characters

003. Longest Substring Without Repeating Characters

难度: Medium

刷题内容

原题连接

内容描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Given a string, find the length of the longest substring without repeating characters.

Example 1:

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

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

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

解题方案

思路 1
**- 时间复杂度: O(N^2)**- 空间复杂度: O(N)**

暴力解法

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param {string} s
* @return {number}
*/
let lengthOfLongestSubstring = function (s) {
let result = 0;
for (let i = 0, len = s.length; i < len; i++) {
let set = new Set();
set.add(s.charAt(i));
for (let j = i + 1; j < len; j++) {
if (set.has(s.charAt(j))) {
break;
}
set.add(s.charAt(j));
}
result = Math.max(result,set.size);
}
return result;
};