给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串
解一:暴力法
public int lengthOfLongestSubstring(String s) {
int res = 0;
int n = s.length();
for(int i = 0;i < n;i++){
for(int j = i;j < n;j++){
Set<Character> set = new HashSet<Character>();
boolean flag = true;
for(int k = i;k < j;k++){
if(set.contains(s.charAt(k))){
flag = false;
break;
}
set.add(s.charAt(k));
}
if(flag)
res = Math.max(res, j - i);
}
}
return res;
}
解二:滑动窗口
利用一个HashSet存储窗口内的已知元素,然好向右扩充该窗口,发现扩充元素在已知窗口内时则移去窗口最左边的元素,再将窗口左边右移一个元素,若不在,向set添加该扩充元素,窗口右边右移一位并此时更新结果。
public int lengthOfLongestSubstring(String s){
int res = 0, left = 0, right = 0;
int n = s.length();
Set<Character> set = new HashSet<Character>();
while (left < n && right < n){
if(!set.contains(s.charAt(right))){
set.add(s.charAt(right++));
res = Math.max(res, right - left);
}else {
set.remove(s.charAt(left++));
}
}
return res;
}
解三:优化滑动窗口
public int lengthOfLongestSubstring(String s){
int res = 0, left = 0, right = 0;
int n = s.length();
Map<Character, Integer> map = new HashMap<Character, Integer>();
for(right = 0;right < n;right++){
if(map.containsKey(s.charAt(right))){
left = Math.max(left, map.get(s.charAt(right)));
}
res = Math.max(res, right - left + 1);
map.put(s.charAt(right), right + 1);
}
return res;
}
使用128大小的数组代替map,因为ASCII码一共128位。
public int lengthOfLongestSubstring(String s){
int res = 0, left = 0, right = 0, n = s.length();
int[] ascii = new int[128];
for(;right < n;right++){
if(ascii[s.charAt(right)] != 0){
left = Math.max(left, ascii[s.charAt(right)]);
}
res = Math.max(res, right - left + 1);
ascii[s.charAt(right)] = right + 1;
}
return res;
}