File tree 1 file changed +7
-15
lines changed
solution/0003.Longest Substring Without Repeating Characters
1 file changed +7
-15
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
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 ;
10
3
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 ;
15
9
}
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 );
19
12
}
20
-
21
13
return max ;
22
14
}
23
15
}
You can’t perform that action at this time.
0 commit comments