[LeetCode] Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
用两个指针,一个指向当前子串的头,一个指向尾,尾指针不断往后扫描,当有字符前面出现过了,记录当前子串长度和最优解的比较结果。然后头指针不断往后扫描,直到扫描到一个字符和尾指针相同,则尾指针继续扫描,当尾指针到达字符串结尾,算法结束。复杂度O(n) + O(n) = O(n)
1 class Solution { 2 private: 3 bool canUse[256]; 4 public: 5 int lengthOfLongestSubstring(string s) { 6 // Start typing your C/C++ solution below 7 // DO NOT write int main() function 8 memset(canUse, true, sizeof(canUse)); 9 10 int count = 0; 11 int start = 0; 12 int ret = 0; 13 for(int i = 0; i < s.size(); i++) 14 { 15 if (canUse[s[i]]) 16 { 17 canUse[s[i]] = false; 18 count++; 19 } 20 else 21 { 22 ret = max(ret, count); 23 while(true) 24 { 25 canUse[s[start]] = true; 26 count--; 27 if (s[start] == s[i]) 28 break; 29 start++; 30 } 31 start++; 32 canUse[s[i]] = false; 33 count++; 34 } 35 } 36 37 ret = max(ret, count); 38 39 return ret; 40 } 41 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探