无重复字符的最长子串(longest-substring-without-repeating-characters)
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
方法一:暴力法
通过两层循环来判断
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);
}
return true;
}
}
方法二:滑动窗口
题目中最关键的条件,无重复字符的子串,观察子串:
红色方框中的枚举均无意义,因为蓝色方框中已出现了重复字符。
绿色方框中的也无意义,因为后续的枚举不会出现满足条件的更优子串。
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<Character>();
int ans = 0,i = 0,j = 0;
while(i<n && j<n) {
//try to extend the range [i,j]
if(!set.contains(s.charAt(j))) {
//添加字符,j向右滑动
set.add(s.charAt(j));
j++;
ans = Math.max(ans, j-i);
}else {
//移除前面的字符,i向右滑动
set.remove(s.charAt(i));
i++;
}
}
return ans;
}
}