Voyz's Studio.

LeetCode算法笔记-滑动窗口——最长不重复子字符串长度

字数统计: 121阅读时长: 1 min
2020/11/27 Share

LeetCode算法笔记–Day31

3. Longest Substring Without Repeating Characters

题目:

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

example
input: “abcabcbb”
output: 3 (“abc”)

example
input: “pwwkew”
output: 3 (“wke”)

My Answer:

1.Hash Map

Time complexity : O(n)
Space complexity : O(n)

6.cc528cb2.jpg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
if(s.length == 0) return 0;

let _start = 0,_end = 0,_res = 0;
let _map = new Map();

while(_end < s.length){
if(_map.has(s[_end])){
_start = Math.max(_start,_map.get(s[_end])+1);
}
_res = Math.max(_res,_end-_start+1);
_map.set(s[_end],_end);
_end += 1;
}

return _res;
};

Snip20200727_1.png

CATALOG
  1. 1. LeetCode算法笔记–Day31
  2. 2. 3. Longest Substring Without Repeating Characters
    1. 2.0.0.0.1. 题目:
    2. 2.0.0.0.2. My Answer: