解题思路:滑动窗口
滑动窗口右边界不断右移,只要没有重复的字符,就继续向右移动;
一旦出现了重复字符,就要缩小左边界,直到重复字符移出了左边界;
然后继续移动右边界。
每次移动需要计算当前长度,并判断是否需要更新最大长度,最终最大的值就是所求。
import java.util.HashSet;
import java.util.Set;
public class Project002 {
public static void main(String[] args) {
String s = "pwwkew";// bbbbbbbbb //zxczxczxc
int l = lengthOfLongestString(s);
System.out.println(l);
}
public static int lengthOfLongestString(String str) {
int len = str.length(); //字符串长度
int result = 0; //结果
int left = 0; //左边界
int right = 0; //右边界
Set set = new HashSet<Character>();
if (len == 0) {
return 0;
}
char[] chars = str.toCharArray();
/*左边界小于长度&& 剩余长度大于已记录的结果*/
while (left < len && len - left > result) {
/*右边界未到头&& set中不包含当前值*/
if (right + 1 < len && !set.contains(chars[right])) {
/*符合条件,移动右边界*/
set.add(chars[right]);
right++;
}else{
/*不符合条件,移动左边界*/
set.remove(chars[left]);
left++;
}
result = Math.max(result,right - left);
}
return result;
}
}