Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 95a978c

Browse files
Update Solution.java to problems 0003
1 parent 2d8fb24 commit 95a978c

File tree

1 file changed

+7
-15
lines changed
  • solution/0003.Longest Substring Without Repeating Characters

1 file changed

+7
-15
lines changed
Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,15 @@
11
class Solution {
22
public int lengthOfLongestSubstring(String s) {
3-
if (s == null || s.length() == 0) {
4-
return 0;
5-
}
6-
char[] chars = s.toCharArray();
7-
int len = chars.length;
8-
int p = 0, q = 0;
9-
int max = 0;
103
Map<Character, Integer> map = new HashMap<>();
11-
while (q < len) {
12-
if (map.containsKey(chars[q])) {
13-
// 防止p指针回溯,导致计算到重复字符的长度
14-
p = Math.max(p, map.get(chars[q]) + 1);
4+
int max = 0;
5+
for (int fast = 0, slow = 0; fast < s.length(); fast ++) {
6+
if (map.containsKey(s.charAt(fast))) {
7+
int target = map.get(s.charAt(fast)) + 1;
8+
slow = target < slow ? slow : target;
159
}
16-
map.put(chars[q], q);
17-
max = Math.max(max, q - p + 1);
18-
++q;
10+
map.put(s.charAt(fast), fast);
11+
max = Math.max(max, fast - slow + 1);
1912
}
20-
2113
return max;
2214
}
2315
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /