leetcode-3 无重复字符的最长子串

题目描述:给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> need = new HashMap<>();

int left = 0, right = 0, start = 0, len = 0;
while (right < s.length()) {
char c = s.charAt(right);
right++;
need.merge(c, 1, (oldVal, newVal) -> ++oldVal);
while (need.get(c).equals(2)) {
if (right - 1 - left > len) {
start = left;
len = right - 1 - left;
}
char l = s.charAt(left);
left++;
need.compute(l, (k, v) -> --v);
}
}
return right - left > len ? right - left : len;
}
}