|
5 | 5 | * 假设字符串中只包含'a'~'z'之间的字符,例如在字符串"arabcacfr"中,最长的不含重复字符的子字符串是"acfr",长度为4 |
6 | 6 | */ |
7 | 7 | public class LongestSubstring { |
8 | | - public int findLongestSubstring(String str) { |
| 8 | + public int lengthOfLongestSubstring(String str) { |
| 9 | + if (str == null || str.length() == 0) return 0; |
9 | 10 | int curLen = 0; |
10 | 11 | int maxLen = 0; |
11 | 12 | // 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++) { |
14 | 15 | position[i] = -1; |
15 | 16 | } |
16 | 17 |
|
17 | 18 | for (int i = 0; i < str.length(); i++) { |
18 | | - int preIndex = position[str.charAt(i) - 'a']; |
| 19 | + int preIndex = position[str.charAt(i)]; |
19 | 20 | // 字符第一次出现,或者d > f(i -1) |
20 | 21 | if (preIndex == -1 || i - preIndex > curLen) curLen++; |
21 | 22 | // d <= f(i -1) |
22 | | - else curLen = i - preIndex; |
| 23 | + else { |
| 24 | + curLen = i - preIndex; |
| 25 | + } |
23 | 26 | // 记录当前字符出现的位置 |
24 | | - position[str.charAt(i) - 'a'] = i; |
| 27 | + position[str.charAt(i)] = i; |
25 | 28 | if (curLen > maxLen) maxLen = curLen; |
26 | 29 | } |
27 | 30 | return maxLen; |
28 | | - } |
29 | 31 |
|
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; |
48 | 32 | } |
49 | 33 |
|
50 | 34 | public static void main(String[] args) { |
51 | 35 | LongestSubstring l = new LongestSubstring(); |
52 | | - System.out.println(l.findLongestSubstring("abcdefaz")); |
| 36 | + System.out.println(l.lengthOfLongestSubstring("abcdefaz")); |
53 | 37 | } |
54 | 38 | } |
0 commit comments