LeetCode - Longest Substring Without Repeating Characters
2013.12.1 19:50
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.
Solution:
Given a string containing only alphabets, find out the length of the longestest substring that contains no repeating characters. Here we display an example:
abcdeedeeabec
The bold part of the string is the target we desire. Here is how my code works:
1. scan the string from left to right, just once
2. for every character we encounter, use an array of size 256 to record position of appearance of every character. For example, the character 'b' appears first at position 1(0-based). This helps us detect repeating characters with O(1) time.
3. Use two pointer $left and $right to record the substring, if the character at right] causes duplicates, we'll have to move $left forward until the duplicate confict is resolved, explained with an example, too:
abcdeedeeabec -> abcdeedeeabec->abcdeedeeabec
When $right reaches position 5, the character 'e' conflicts with the 'e' at position 4. Then we'll have to move $left beyond position 4 to resolve the conflict.
4. When the conflict is resolved, continue moving $right forward until it reaches the end.
5. During the whole process, record the maximum length, that's the answer we need.
Time complexity is strictly O(n) with one scan of the array. Space complexity is O(1), requires an array of size 256, that's still O(1), right?
Accepted code:
1 // 1AC, fast and clear, good work! O(n) complexity 2 class Solution { 3 public: 4 int lengthOfLongestSubstring(string s) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 int i, j, len; 8 int maxlen; 9 10 len = s.length(); 11 if(len <= 1){ 12 return len; 13 } 14 15 // record the emergence of each alphabet 16 int a[256]; 17 18 for(i = 0; i < 256; ++i){ 19 a[i] = 0; 20 } 21 22 ++a[s[0]]; 23 i = 0; 24 j = 1; 25 maxlen = j - i; 26 while(true){ 27 if(i >= len){ 28 break; 29 } 30 while(j < len && a[s[j]] == 0){ 31 ++a[s[j]]; 32 ++j; 33 if(j - i > maxlen){ 34 maxlen = j - i; 35 } 36 } 37 if(j >= len){ 38 break; 39 } 40 while(a[s[j]] > 0){ 41 --a[s[i]]; 42 ++i; 43 } 44 } 45 return maxlen; 46 } 47 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)