File tree Expand file tree Collapse file tree 1 file changed +4
-31
lines changed
src/main/java/name/guolanren/_1to100/_1to10/p3 Expand file tree Collapse file tree 1 file changed +4
-31
lines changed Original file line number Diff line number Diff line change 12
12
public class LongestSubstringWithoutRepeatingCharacters {
13
13
14
14
public int lengthOfLongestSubstring (String s ) {
15
- int length = s .length ();
16
15
int max = 0 ;
17
- int from = 0 ;
18
16
Map <Character , Integer > record = new HashMap <>();
19
- for (int i = 0 ; i < length ; i ++) {
20
- if (length - from <= max ) {
21
- break ;
22
- }
17
+ for (int i = 0 , j = 0 ; i < s .length (); i ++) {
23
18
Character c = s .charAt (i );
24
19
Integer idx = record .get (c );
25
- if (idx == null || idx < from ) {
26
- max = Math .max (max , i - from + 1 );
20
+ if (idx == null || idx < j ) {
21
+ max = Math .max (max , i - j + 1 );
27
22
} else {
28
- from = idx + 1 ;
23
+ j = idx + 1 ;
29
24
}
30
25
record .put (c , i );
31
26
}
32
27
return max ;
33
28
}
34
29
35
- // public int lengthOfLongestSubstring(String s) {
36
- // int maxLength = 0;
37
- // int byeIndex = 0;
38
- // // 乱序的候选最长字符串
39
- // Set<Character> candidate = new HashSet<>();
40
- // for (int i = 0; i < s.length(); i++) {
41
- // // 已经追不上啦,放弃吧
42
- // if (s.length() - i + candidate.size() <= maxLength) {
43
- // break;
44
- // }
45
- // char c = s.charAt(i);
46
- // // 遇到重复的,按顺序删除,直到跟相同的字符说 bye 为止
47
- // while (candidate.contains(c)) {
48
- // char bye = s.charAt(byeIndex++);
49
- // candidate.remove(bye);
50
- // }
51
- // candidate.add(c);
52
- // maxLength = Integer.max(maxLength, candidate.size());
53
- // }
54
- // return maxLength;
55
- // }
56
-
57
30
}
You can’t perform that action at this time.
0 commit comments