Skip to content

Commit fcc97ae

Browse files
committed
fd
1 parent 8e0c0d7 commit fcc97ae

File tree

2 files changed

+37
-15
lines changed

2 files changed

+37
-15
lines changed

leetcode/solution/src/LongestSubstringWithoutRepeatingCharacters.java

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,17 @@
33
*/
44
public class LongestSubstringWithoutRepeatingCharacters {
55

6-
// 耗时39ms,性能挺好
76
public int lengthOfLongestSubstring(String s) {
87
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)]--;
1914
}
15+
max = Math.max(max, i - j + 1);
2016
}
21-
22-
return maxLen;
17+
return max;
2318
}
2419
}

leetcode/src/Main.java

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,43 @@
11
import com.sun.org.apache.xpath.internal.operations.Bool;
22

33
import java.util.*;
4+
import java.util.concurrent.*;
45

56
public class Main {
67

78
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+
}
823

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;
1136
}
37+
1238
}
1339

40+
1441
public static void main(String[] args) {
1542
Solution s = new Solution();
1643
}

0 commit comments

Comments
 (0)