3无重复字符的最长子串
- 题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 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 由英文字母、数字、符号和空格组成
-
题解思路
方法一
穷举所有的子串(定义两个函数):①第一个函数穷举所有可能出现的子串结果,对于字符串的每一个字符,它所构成的子串是下标比它大的所有子串组合
eg:abc 对于a,子串有a, ab,abc, 对于b,子串有b,bc, 对于c,有子串c 所以字符串abc的所有的子串为a,ab,abc,b,bc,c
②第二个函数用户过滤穷举出来的子串是否重复,用hashset
时间复杂度o(n^3)这种方法会超时
/**
* desc: 暴力枚举,超时
*
* @param s 字符串
* @return 无重复的最长字串的长度
*/
public static int lengthOfLongestSubstringV1(String s) {
int res = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j <= s.length(); j++) {
//看字串是否含有重复字符
if (isTrue(s, i, j)) {
//看滑窗长度j-i和res谁大,取最大值,则为最长字串长度
res = Math.max(res, j - i);
}
}
}
return res;
}
/**
* desc: 判断字符串是否有重复字符
*
* @param s 字符串
* @param start 起始位置
* @param end 结束位置
* @return 是否有重复:true=无重复,false=有重复
*/
public static boolean isTrue(String s, int start, int end) {
Set<Character> set = new HashSet<>();
for (int i = start; i < end; i++) {
if (set.contains(s.charAt(i))) {
return false;
}
set.add(s.charAt(i));
}
return true;
}
方法二
滑动窗口法
定义两个指针,start和end,代表当前窗口的开始和结束位置,同样使用hashset,当窗口中出现重复的字符时,start++,没有重复时,end++,每次更新长度的最大值
时间复杂度o(n)
/**
* desc: 滑动窗口,当窗口中出现重复的字符时,start++,没有重复时,end++,每次更新长度的最大值,时间复杂度O(n)
*
* @param s 字符串
* @return 无重复的最长字串的长度
*/
public static int lengthOfLongestSubstringV2(String s) {
// 无重复的最长字串的长度
int res = 0;
// 字符串长度
int n = s.length();
// 左指针
int start = 0;
// 右指针
int end = 0;
// 存储字符
Set<Character> set = new HashSet<>();
while (start < n && end < n) {
//当右指针的字符已经有了的时候,移除左指针的字符,左指针右移一位(向右滑动一次)
if (set.contains(s.charAt(end))) {
set.remove(s.charAt(start++));
} else {
//当右指针的字符没有重复出现,把右指针的字符添加进set,右指针右移一位(向右滑动一次)
set.add(s.charAt(end++));
//看滑窗长度end-start和res谁大,取最大值,则为最长字串长度
res = Math.max(res, end - start);
}
}
return res;
}
方法三
由方法二得到的滑动窗口,每次在[start,end]中如果有重复的,我们的做法是更新窗口从end重新开始,这种方法要求定义一个hashmap保存字符到索引的映射,并且每次都会更新map的值
时间复杂度o(n)
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int res = 0;
int end=0,start=0;
Map<Character,Integer> map=new HashMap<>();
for(;start<n && end<n;end++){
if(map.containsKey(s.charAt(end))){
start=Math.max(map.get(s.charAt(end)),start);//从有重复的下一个位置继续找
}
map.put(s.charAt(end),end+1);//map每次更新
res=Math.max(res,end-start+1);//结果每次更新
}
return res;
}
}
/*
eg abca
start end res map 滑动窗口范围
0 0 1 a->1 a
0 1 2 a->1,b->2 a,b
0 2 3 a->1,b->2,c->3 a,b,c
1 3 3 a->4,b->2,c->3 b,c,a
*/