C++版- Leetcode 3. Longest Substring Without Repeating Characters解题报告 编辑
Leetcode 3. Longest Substring Without Repeating Characters
提交网址: https://leetcode.com/problems/longest-substring-without-repeating-characters/
Total Accepted: 149135 Total Submissions: 674678 Difficulty: Medium
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
分析:
使用哈希表,保存每个字符上一次出现的位置,时间复杂度为O(n).
AC代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int loc[256]; // 哈希表保存字符上一次出现的位置,ASCII码是8位,一般用前7位,是128(2^7)个可用字符。IBM机器的扩展使用了最高位,故用2^8个(256)
memset(loc, -1, sizeof(loc));
int curStartIdx = -1, max_len = 0; //curStartIdx为当前子串的开始位置,初始化为-1
for(int i = 0; i < s.size(); i++)
{
if(loc[s[i]] > curStartIdx) //如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1
{
curStartIdx = loc[s[i]];
}
if(i - curStartIdx > max_len) // 使用贪心算法进行子串延伸,关键!!!
{
max_len = i - curStartIdx;
}
loc[s[i]] = i; //如果当前字符没出现过,将其位置记录在loc数组中
}
return max_len;
}
};
You are here!
Your runtime beats 61.72% of cppsubmissions.
如果,您希望更容易地发现我的新文章,不妨点击一下绿色通道的【关注我】,亦可微信搜索公众号「大白技术控」关注我。
如果您觉得阅读本文对您有帮助,请点击一下右下方的推荐按钮,您的推荐将是我写作的最大动力!版权声明:本文为博主原创或转载文章,欢迎转载,但转载文章之后必须在文章页面明显位置注明出处,否则保留追究法律责任的权利。如您有任何疑问或者授权方面的协商,请 .
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?