s 由英文字母、数字、符号和空格组成
class Solution {
public int lengthOfLongestSubstring(String s) {
int length=0;
//双指针
int right = 0,left=0;
while (right<s.length()){
String sub;
if(right==s.length()-1){
sub=s.substring(left);
length=Math.max(length,sub.length());
break;
}else {
sub= s.substring(left,right+1);
int index = sub.indexOf(s.charAt(right+1));
if(index!=-1){//包含
length=Math.max(length,sub.length());
left++;
}else {
right++;
}
}
}
return length;
}
}
class Solution {
public int lengthOfLongestSubstring(String s) {
// 哈希集合,记录每个字符是否出现过
Set<Character> occ = new HashSet<Character>();
int right=-1,length=0;//右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动
for(int left=0;left<s.length();left++){
//左指针移动一个,集合减少
if(left!=0) occ.remove(s.charAt(left-1));
//移动右指针
while (right+1<s.length()&&!occ.contains(s.charAt(right+1))){
occ.add(s.charAt(right+1));
right++;
}
length=Math.max(length,right-left+1);
}
return length;
}
}