LeetCode 3. Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
复制Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.
实现思路:
题意是找到一个串中字符不重复的最大字串(不包括串本身),和KMP算法的题目看起来很相似,但KMP的应用常用于在一个文本串 S 内查找一个模式串 P 的出现位置,本题可以借鉴KMP的滑动窗口模式,这种滑动窗口模式在字符串题型中非常常见。
AC代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxLen=0,cnt=0;
string temp;
for(int i=0; i<s.length(); i++) {
if(temp.find(s[i])==string::npos) {
temp+=s[i];//找不到当前窗口的字母则添加
} else {
if(temp.size()>maxLen) maxLen=temp.size();
temp=temp.substr(1);//遇到重复情况了例如dvcd 此时temp="dvc"所以截取temp="vc"即可
i--;//重新滑动窗口到原来重复的窗口位置进行添加
}
}
if(temp.size()>maxLen) maxLen=temp.size();//这是考虑只有一个窗口或者最后一个不重复窗口的情况
return maxLen;
}
};
标签:
LeetCode题库
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· MySQL下200GB大表备份,利用传输表空间解决停服发版表备份问题
· 记一次 .NET某固高运动卡测试 卡慢分析
· 微服务架构学习与思考:微服务拆分的原则
· 记一次 .NET某云HIS系统 CPU爆高分析
· 如果单表数据量大,只能考虑分库分表吗?
· 7 个最近很火的开源项目「GitHub 热点速览」
· DeepSeekV3:写代码很强了
· 记一次 .NET某固高运动卡测试 卡慢分析
· Visual Studio 2022 v17.13新版发布:强化稳定性和安全,助力 .NET 开发提
· MySQL下200GB大表备份,利用传输表空间解决停服发版表备份问题