[每日算法] leetcode第3题:无重复字符的最长子串
题目描述
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解法1:暴力破解
逐个生成子串
判断子串是否包含重复字符
时间复杂度:
找到所有子串 O(n^2)
判断子串是否包含重复字符 HashSet O(n),双指针O(n^2)
整体复杂度O(n^3)
空间复杂度:
HashSet O(n)
⚠️注:该方法复杂度过高,在leetCode提交会超时,这里就不在出代码示例。
解法2: 滑动窗口
关键字:重复字符 -> 出现1次以上
模式识别1: 出现次数 代表 将使用散列表 (记录次数,参考专栏leetcode第一题讲解)
构建子串 :散列表存储下标
模式识别2: 涉及到子串,考虑滑动窗口
滑动窗口滑动规则:当遇到子串就是窗口中的串存在的字符时,窗口向右滑动,使得窗口正好跨过第一个重复字符(思考:为什么不是第二个?)
窗口的表现形式:开始坐标、窗口长度两个变量。
import java.util.*;
class Solution {
public int lengthOfLongestSubstring(String s) {
Hashtable<Character,Integer> table = new Hashtable();
int maxLength = 0;
int currentLength = 0;
int startIndex = 0;
char[] arr = s.toCharArray();
for(int i=0;i<arr.length;i++){
if(null == table.get(arr[i]) || table.get(arr[i])<startIndex){
currentLength++;
}
else{
//缩放窗口
startIndex = table.get(arr[i]);
currentLength = i-startIndex;
}
table.put(arr[i],i);
if(currentLength>maxLength){
maxLength = currentLength;
}
}
return maxLength;
}
}
时间复杂度:O(n)
空间复杂度:O(n)

浙公网安备 33010602011771号