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;
    }
};
原文地址:https://www.cnblogs.com/zl1991/p/4714077.html