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.

第一次完全没有找参考做出来的题,开心。

复制代码
 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         int n=s.size();
 5         if(n<2) return n;
 6         map<char,int> strmap;
 7         int begin=0;
 8         int end=0;
 9         int res=0;
10         for(int i=0;i<n;i++)
11         {
12             if(strmap.find(s[i])==strmap.end())
13             {
14                 strmap.insert(pair<char,int>(s[i],i));
15                 end=i;
16             }
17             else
18             {
19                 if((end-begin+1)>res) res=end-begin+1;
20                 if(begin<=strmap[s[i]]) begin=strmap[s[i]]+1;
21                 end=i;
22                 strmap[s[i]]=i;
23             }
24         }
25         if((end-begin+1)>res) res=end-begin+1;
26         return res;
27     }
28 };
复制代码

 更新:

这里可以建立一个 HashMap,建立每个字符和其最后出现位置之间的映射,然后需要定义两个变量 res 和 left,其中 res 用来记录最长无重复子串的长度,left 指向该无重复子串左边的起始位置的前一个,由于是前一个,所以初始化就是 -1,然后遍历整个字符串,对于每一个遍历到的字符,如果该字符已经在 HashMap 中存在了,并且如果其映射值大于 left 的话,那么更新 left 为当前映射值。然后映射值更新为当前坐标i,这样保证了 left 始终为当前边界的前一个位置,然后计算窗口长度的时候,直接用 i-left 即可,用来更新结果 res。

复制代码
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.empty())
            return 0;
        unordered_map<char,int> m;
        int max=0,l=-1;
        for(int i=0;i<s.size();++i)
        {
            if(m.count(s[i])&&m[s[i]]>l)
                l=m[s[i]];
            int t=i-l;
            if(t>max) max=t;
            m[s[i]]=i;
        }
        return max;
    }
};
复制代码

 

posted @   鸭子船长  阅读(182)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示