给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
正文开始
public class NoRepeatingCharacters {
public static int lengthOfLongestSubstring(String s) {
int len = s.length();
int start = 0;//窗口开始的下标
int end = 0;//窗口末尾的下标
int max = 0;//记录出现过的最大长度子串
HashSet set = new HashSet();//存字符,判断重复
while(start < len && end < len){
if(set.contains(s.charAt(end))){//判断字符是否存在
set.remove(s.charAt(start++));//窗口向右移动
}else {
set.add(s.charAt(end++));//不存在则添加
max = Math.max(max,end-start);//(end-start)窗口当前长度
}
}
return max;
}
public static void main(String[] args) {
String s = "abcabcbb";
int i = NoRepeatingCharacters.lengthOfLongestSubstring(s);
System.out.println(i);
}
}
运行结果