给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
示例 4:
输入: s = ""
输出: 0
提示:
0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
public int lengthOfLongestSubstring(String s) {
if(s==null||s.length()==0)
return 0;
int max=0;
HashSet<Character> set=new HashSet<>();
for(int i=0;i<s.length();i++)
{
int count=0;
for(int cur=i;cur<s.length();cur++)
{
if(set.contains(s.charAt(cur)))
{
set.clear();
break;
}else
{
set.add(s.charAt(cur));
count++;
}
max=max>count?max:count;
}
}
return max;
}
public int lengthOfLongestSubstring(String s) {
if(s==null||s.length()==0)
return 0;
int max=0;
int left=0;
HashMap<Character,Integer> map=new HashMap<>();
for(int i=0;i<s.length();i++)
{
if(map.containsKey(s.charAt(i)))
{
left=Math.max(left,map.get(s.charAt(i))+1);
}
max=Math.max(i-left+1,max);//因为i点适配失败,所以left也向右移动了1所以i-left+1,相当于是i没移动之前的最长序列。
map.put(s.charAt(i),i);
}
return max;
}
滑动窗口好理解版
首先要对字符串进行遍历,在遍历的过程中加入一个set集合,当没有重复值的时候每次遍历窗口都会增大一点这个增大体现在curlen,但是一旦遇到相同的数字,那么窗口就要缩小,缩小到没有当前值,然后从当前的位置开始重新扩大窗口的值,这样就能找到最大的窗口了
public int lengthOfLongestSubstring(String s) {
if(s==null||s.length()==0)
return 0;
int max=0;
int curlen=0;
int left=0;
HashSet<Character> set=new HashSet<>();
for(int i=0;i<s.length();i++)
{
curlen++;//当前长度
while (set.contains(s.charAt(i)))
{
set.remove(s.charAt(left));
left++;
curlen--;
}
set.add(s.charAt(i));
max=Math.max(curlen,max);
}
return max;
}