题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/
题意:找出无重复字符的最长子串
思路:
方法一:滑动窗口,用HashSet判断字符是否存在,右端先增,无法增时左端增
方法二:遍历一遍,维护每个字符出现的最右位置
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ans=0;
int a[300];
memset(a,-1,sizeof(a));
int len=s.length();
int l=0;
for(int i=0;i<len;i++)
{
l=max(l,a[s[i]]+1);
ans=max(ans,i-l+1);
a[s[i]]=i;
}
return ans;
}
};
本文介绍了解决LeetCode上“最长子串无重复字符”问题的两种方法:滑动窗口与一次遍历。通过维护字符的最后出现位置,实现了高效求解最长无重复子串长度的目标。
721

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



