File tree Expand file tree Collapse file tree 2 files changed +37
-15
lines changed Expand file tree Collapse file tree 2 files changed +37
-15
lines changed Original file line number Diff line number Diff line change 3
3
*/
4
4
public class LongestSubstringWithoutRepeatingCharacters {
5
5
6
- // 耗时39ms,性能挺好
7
6
public int lengthOfLongestSubstring (String s ) {
8
7
int [] count = new int [256 ];
9
-
10
- int maxLen = 0 ;
11
-
12
- for (int i = 0 , j = 0 ; j < s .length (); ) {
13
- if (count [s .charAt (j )] == 0 ) {
14
- count [s .charAt (j )]++;
15
- maxLen = Math .max (maxLen , j - i + 1 );
16
- j ++;
17
- } else {
18
- --count [s .charAt (i ++)];
8
+ int max = 0 ;
9
+ for (int i = 0 , j = 0 ; i < s .length (); i ++) {
10
+ char c = s .charAt (i );
11
+ count [c ]++;
12
+ for ( ; j < i && count [c ] > 1 ; j ++) {
13
+ count [s .charAt (j )]--;
19
14
}
15
+ max = Math .max (max , i - j + 1 );
20
16
}
21
-
22
- return maxLen ;
17
+ return max ;
23
18
}
24
19
}
Original file line number Diff line number Diff line change 1
1
import com .sun .org .apache .xpath .internal .operations .Bool ;
2
2
3
3
import java .util .*;
4
+ import java .util .concurrent .*;
4
5
5
6
public class Main {
6
7
7
8
public static class Solution {
9
+ public int lengthOfLongestSubstring (String s ) {
10
+ HashMap <Character , Integer > map = new HashMap <>();
11
+ int max = 0 ;
12
+ for (int i = 0 , j = 0 ; i < s .length (); i ++) {
13
+ char c = s .charAt (i );
14
+ map .put (c , map .getOrDefault (c , 0 ) + 1 );
15
+ for ( ; j < i && map .get (c ) > 1 ; j ++) {
16
+ char cc = s .charAt (j );
17
+ map .put (cc , map .get (cc ) - 1 );
18
+ }
19
+ max = Math .max (max , i - j + 1 );
20
+ }
21
+ return max ;
22
+ }
8
23
9
- public TreeNode pruneTree (TreeNode root ) {
10
-
24
+ public int lengthOfLongestSubstring (String s ) {
25
+ int [] count = new int [256 ];
26
+ int max = 0 ;
27
+ for (int i = 0 , j = 0 ; i < s .length (); i ++) {
28
+ char c = s .charAt (i );
29
+ count [c ]++;
30
+ for ( ; j < i && count [c ] > 1 ; j ++) {
31
+ count [s .charAt (j )]--;
32
+ }
33
+ max = Math .max (max , i - j + 1 );
34
+ }
35
+ return max ;
11
36
}
37
+
12
38
}
13
39
40
+
14
41
public static void main (String [] args ) {
15
42
Solution s = new Solution ();
16
43
}
You can’t perform that action at this time.
0 commit comments