LeetCode 3. 无重复字符的最长子串(Java版)
方法一
穷举所有的子串(定义两个函数):
①第一个函数穷举所有可能出现的子串结果,对于字符串的每一个字符,它所构成的子串是下标比它大的所有子串组合
eg:abc
对于a,子串有a, ab,abc,
对于b,子串有b,bc,
对于c,有子串c
所以字符串abc的所有的子串为a,ab,abc,b,bc,c
②第二个函数用户过滤穷举出来的子串是否重复,用hashset
时间复杂度o(n^3)这种方法会超时
-
class Solution {
-
public int lengthOfLongestSubstring(String s) {
-
int res=0;
-
for(int i=0;i<s.length();i++){
-
for(int j=i+1;j<=s.length();j++){
-
if(isTrue(s,i,j))
-
res=Math.max(res,j-i);
-
}
-
}
-
return res;
-
}
-
public boolean isTrue(String s ,int start,int end){
-
Set<Character> set=new HashSet<>();
-
for(int i=start;i<end;i++){
-
if(set.contains(s.charAt(i)))
-
return false;
-
set.add(s.charAt(i));
-
}
-
return true;
-
}
-
}
方法二
滑动窗口法:
定义两个指针,start和end,代表当前窗口的开始和结束位置,同样使用hashset,当窗口中出现重复的字符时,start++,没有重复时,end++,每次更新长度的最大值
时间复杂度o(n)
-
public class Solution {
-
public int lengthOfLongestSubstring(String s) {
-
int n = s.length();
-
int res = 0;
-
int end=0,start=0;
-
Set<Character> set=new HashSet<>();
-
while(start<n && end<n){
-
if(set.contains(s.charAt(end))){
-
set.remove(s.charAt(start++));
-
}else{
-
set.add(s.charAt(end++));
-
res=Math.max(res,end-start);
-
}
-
-
}
-
return res;
-
}
-
-
-
}
方法三
由方法二得到的滑动窗口,每次在[start,end]中如果有重复的,我们的做法是更新窗口从end重新开始,这种方法要求定义一个hashmap保存字符到索引的映射,并且每次都会更新map的值
时间复杂度o(n)
-
public class Solution {
-
public int lengthOfLongestSubstring(String s) {
-
int n = s.length();
-
int res = 0;
-
int end=0,start=0;
-
Map<Character,Integer> map=new HashMap<>();
-
for(;start<n && end<n;end++){
-
if(map.containsKey(s.charAt(end))){
-
start=Math.max(map.get(s.charAt(end)),start);//从有重复的下一个位置继续找
-
}
-
map.put(s.charAt(end),end+1);//map每次更新
-
res=Math.max(res,end-start+1);//结果每次更新
-
}
-
return res;
-
}
-
}
-
/*
-
eg abca
-
start end res map 滑动窗口范围
-
0 0 1 a->1 a
-
0 1 2 a->1,b->2 a,b
-
0 2 3 a->1,b->2,c->3 a,b,c
-
1 3 3 a->4,b->2,c->3 b,c,a
-
*/

浙公网安备 33010602011771号