Skip to content

Commit 67c8ca8

Browse files
authored
Update LongestSubstring.java
1 parent f494fcc commit 67c8ca8

File tree

1 file changed

+10
-26
lines changed

1 file changed

+10
-26
lines changed

code/offer/src/Chap5/LongestSubstring.java

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,50 +5,34 @@
55
* 假设字符串中只包含'a'~'z'之间的字符,例如在字符串"arabcacfr"中,最长的不含重复字符的子字符串是"acfr",长度为4
66
*/
77
public class LongestSubstring {
8-
public int findLongestSubstring(String str) {
8+
public int lengthOfLongestSubstring(String str) {
9+
if (str == null || str.length() == 0) return 0;
910
int curLen = 0;
1011
int maxLen = 0;
1112
// 0~25表示a~z,position[0] = index,表明a上次出现在index处
12-
int[] position = new int[26];
13-
for (int i = 0; i < 26; i++) {
13+
int[] position = new int[256];
14+
for (int i = 0; i < 256; i++) {
1415
position[i] = -1;
1516
}
1617

1718
for (int i = 0; i < str.length(); i++) {
18-
int preIndex = position[str.charAt(i) - 'a'];
19+
int preIndex = position[str.charAt(i)];
1920
// 字符第一次出现,或者d > f(i -1)
2021
if (preIndex == -1 || i - preIndex > curLen) curLen++;
2122
// d <= f(i -1)
22-
else curLen = i - preIndex;
23+
else {
24+
curLen = i - preIndex;
25+
}
2326
// 记录当前字符出现的位置
24-
position[str.charAt(i) - 'a'] = i;
27+
position[str.charAt(i)] = i;
2528
if (curLen > maxLen) maxLen = curLen;
2629
}
2730
return maxLen;
28-
}
2931

30-
public int findLongestSubstring2(String str) {
31-
int curLen = 0;
32-
int maxLen = 0;
33-
int preIndex = -1;
34-
// 0~25表示a~z,position[0] = index,表明a上次出现在index处
35-
int[] position = new int[26];
36-
for (int i = 0; i < 26; i++) {
37-
position[i] = -1;
38-
}
39-
40-
for (int i = 0; i < str.length(); i++) {
41-
preIndex = Math.max(preIndex, position[str.charAt(i) - 'a']);
42-
curLen = i - preIndex;
43-
// 记录当前字符出现的位置
44-
position[str.charAt(i) - 'a'] = i;
45-
maxLen = Math.max(curLen, maxLen);
46-
}
47-
return maxLen;
4832
}
4933

5034
public static void main(String[] args) {
5135
LongestSubstring l = new LongestSubstring();
52-
System.out.println(l.findLongestSubstring("abcdefaz"));
36+
System.out.println(l.lengthOfLongestSubstring("abcdefaz"));
5337
}
5438
}

0 commit comments

Comments
 (0)