4_Longest Substring Without Repeating Characters

Posted taxue505

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4_Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。

//abcabcbb    abc    3
//bbbbb       b      1
//pwwkew      wke    3
#include<iostream>
#include<string>
#include<vector>

using namespace std;

int lengthOfLongestSubstring(string s)

    if(s.size()==0) return 0;
    
    //unodered_map<char,int> map;
    vector<int> map(256,-1);
    
    int maxlen=0,count=0;
    
    for(int i=0;i<s.size();i++)
    
        char c=s[i];
        
        if(map[c]==-1)
        
            count++;
        
        else
        
            // find a match
            //           count
            //  *x*abcx, 3->4
            //  ***xbcx, 3->3
            //  ***axcx, 3->2
            int loc=map[c];
            
            if(loc+count<i)       // case 3->4
                count++;
            else if(loc+count==i) // case 3->3
                ;
            else if(loc+count>i)  // case 3->2
                count=i-loc;
        
        
        map[c]=i;
        
        if(count>maxlen)
            maxlen=count;

    
    return maxlen;


int main()

    string str1="abcabcbb";
    cout<<lengthOfLongestSubstring(str1)<<endl;
    string str2="bbbbb";
    cout<<lengthOfLongestSubstring(str2)<<endl;
    string str3="pwwkew";
    cout<<lengthOfLongestSubstring(str3)<<endl;
    
    return 0;

//g++ Longest_Substring.cc -o Longest_Substring
//./Longest_Substring

以上是关于4_Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

算法_Longest Palindromic Substring(寻找最长回文字串)

LeetCode 5_Longest Palindromic Substring

LeetCode:5_Longest Palindromic Substring | 最长的回文子串 | Medium

leetcode -- Algorithms -- 3_ Longest Substring Without Repeating Characters

3_Longest Substring Without Repeating Characters -- LeetCode

5_Longest Palindromic Substring(Manacher) --LeetCode