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 1212public class LongestSubstringWithoutRepeatingCharacters {
1313
1414 public int lengthOfLongestSubstring (String s ) {
15- int length = s .length ();
1615 int max = 0 ;
17- int from = 0 ;
1816 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 ++) {
2318 Character c = s .charAt (i );
2419 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 );
2722 } else {
28- from = idx + 1 ;
23+ j = idx + 1 ;
2924 }
3025 record .put (c , i );
3126 }
3227 return max ;
3328 }
3429
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-
5730}
You can’t perform that action at this time.
0 commit comments