题目
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
解析
方法一
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
if (n == 0) return 0;
int max = 0;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0, j = 0; i < n; i++) {
if (map.containsKey(s.charAt(i))) {
// + 1是因为重复,向后移动一位
j = Math.max(j, map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i), i);
max = Math.max(max, i - j + 1);
}
return max;
}
}
方法二
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] map = new int[128];
int count = 0, begin = 0, end = 0, d =0;
while (end < s.length()) {
if (map[s.charAt(end++)]++ > 0) count++;//重复
while (count > 0) if (map[s.charAt(begin++)]-- > 1) count--;
d = Math.max(d, end - begin);
}
return d;
}
}