leetcode 3. longest substring without repeating characters [medium]

题目来源:https://leetcode.com/problems/longest-substring-without-repeating-characters/

题目难度:Medium

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class  {
public int lengthOfLongestSubstring(String s) {
int[] freq = new int[256];
int l = 0;
int r = -1;
int res = 0;

while (l < s.length()) {
if (r + 1 >= s.length()) {
break;
} else if (r + 1 < s.length() && freq[s.charAt(r + 1)] == 0) {
freq[s.charAt(++r)]++;
} else {
freq[s.charAt(l++)]--;
}

res = max(res, r - l + 1);
}

return res;
}

private int max(int a, int b) {
return a > b ? a : b;
}
}

思路

动态窗口