探索字节跳动(一)-无重复字符的最长子串
算法一:很容易想到以下这个算法
import java.util.HashSet;
public class Solution{
public int lengthOfLongestSubstring(String s){
int n = s.length();
int ans = 0;
for(int i = 0 ; i < n ; i++){
for(int j = i+1 ; j <= n ; j++){
if(allUnique(s, i, j)){
ans = Math.max(ans,j-i);
}
}
}
return ans;
}
public boolean allUnique(String s,int start,int end){
Set<Character> set = new HashSet<>();
for(int i = start ; i < end ; i++){
Character ch = s.charAt(i);
if(set.contains(ch)) return false;
set.add(ch);
}
}
}
可是运行超时了,应该还有更高效的算法
算法二:遇到重复的字符的时候,移动左边的指针直到所有字符都不相同
class Solution {
public int lengthOfLongestSubstring(String s) {
int ans = 0;
int n = s.length();
int i = 0, j = 0;
Set<Character> set = new HashSet<>();
while(i < n && j < n){
if(!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans,j-i);
}else{
set.remove(s.charAt(i++));
}
}
return ans;
}
}
这样就可以通过了