题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
C++
时间复杂度: O(n)
class Solution {
public:
//滑动窗口
int lengthOfLongestSubstring(string s) {
if(s.size()==0) return 0;
if(s.size()==1) return 1;
unordered_map<char,int> window; //记录当前窗口的各个字符频率
int left=0;
int right=0;
int res=0; //返回值
while(right<s.size()){
char c=s[right];
right++;
window[c]++;
//判断是否存在重复,存在就需要左指针右移直到没有重复
while(window[c]>1){
char d=s[left];
left++;
window[d]--;
}
//没有重复值了,
res=max(res,right-left);
}
return res;
}
};
JAVA
时间复杂度 O(n)
class Solution {
public int lengthOfLongestSubstring(String s) {
int [] last=new int [128]; //记录字符上次出现的位置
for(int i=0;i<128;i++){
last[i]=-1; //初始化
}
int n=s.length();
int res=0;
int start=0; //窗口开始位置
for(int i=0;i<n;i++){
int index=s.charAt(i);
start=Math.max(start,last[index]+1);
res=Math.max(res,i-start+1);
last[index]=i;
}
return res;
}
}
889

被折叠的 条评论
为什么被折叠?



