# LeetCode 3 Longest Substring Without Repeating Characters

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


Example 1:

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


Example 2:

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


Example 3:

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.


Example 4:

Input: s = ""
Output: 0


Constraints:

0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.

/**
* 滑动窗口
* 添加了什么元素就弹出左边元素及其之前的元素
* a b c a b c b b
* [a b c] 3
* a [b c a] 3 添加了a,弹出左边的a
* b [c a b] 3 添加了b,弹出左边的b
* c [a b c] 3 添加了c,弹出左边的c
* a b [c b] 2 添加了b,弹出左边b和b之前所有元素
* c b [b] 1 添加了b,弹出左边b和b之前所有元素
*/
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) {
return 0;
}
HashMap<Character, Integer> map = new HashMap<>();
int max = 0;
int left = 0;

for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
left = Math.max(left, map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i), i);
max = Math.max(max, i - left + i);
}
return max;
}
}


05-21 1087                                                                  07-29 86
04-05 61
07-15 314
04-01 6887
05-03 341
09-01 1万+
05-17 160
11-20 2375
01-12 329
02-26 57
05-22 135
07-28 171
07-24 278
08-24 9063
04-13 380
11-15 150
04-16 3154
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客