【leetcode】Longest Substring Without Repeating Characters

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.

 
 
举个例子:
abcaddbcef
 
abca遇到a后,我们下次从b开始比较
 
bcadd遇到d后,我们下次从d开始比较
 
dbcef结束
 
所以设置一个start_index作为起始位置,遇到重复的元素,起始位置设置在重复元素第一次出现的位置+1
 
复制代码
 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4        
 5         map<char,int> char2index;
 6        
 7         int start_index=0;
 8         int result=0;
 9         int i;
10         for(i=0;i<s.length();i++)
11         {
12             //从来没有出现过的元素
13             if(char2index.find(s[i])==char2index.end())
14             {
15                 char2index[s[i]]=i;
16             }
17             else
18             {
19                 //出现过,且在start_index之后出现
20                 if(char2index[s[i]]>=start_index)
21                 {
22                     result=max(result,i-start_index);
23                     start_index=char2index[s[i]]+1;
24                     char2index[s[i]]=i;
25                 }
26                 else
27                 {
28                     //在start_index之前出现
29                     char2index[s[i]]=i;
30                 }
31  
32             }
33         }
34         result=max(result,i-start_index);
35        
36         return result;
37     }
38 };
复制代码

 

 
 
 
简化版本:
复制代码
 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4        
 5         map<char,int> char2index;
 6        
 7         int start_index=0;
 8         int result=0;
 9         int i;
10         for(i=0;i<s.length();i++)
11         {
12             if(char2index.find(s[i])!=char2index.end()&&char2index[s[i]]>=start_index)
13             {
14                 result=max(result,i-start_index);
15                 start_index=char2index[s[i]]+1;
16             }
17             char2index[s[i]]=i;
18         }
19        
20         result=max(result,i-start_index);
21        
22         return result;
23     }
24 };
复制代码

 

posted @   H5开发技术  阅读(175)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示