首页 > 代码库 > 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.

描述:即最长不重复子序列,具体思路参考我的博文。

O(n)解法。

class Solution {private:    struct myarray{        bool dp;        int loc;    };public:    int lengthOfLongestSubstring(string s) {        if(s.empty())            return 0;        struct myarray dps[1000];        for (int i=0; i<1000; ++i) {            dps[i].dp=false;            dps[i].loc=-1;        }        int reslen=0;        int nextStart=0;        int i;        for(i=0;i<s.size();++i)        {            if(dps[s[i]].dp==false)            {                dps[s[i]].dp=true;                dps[s[i]].loc=i;            }            else            {                if(i-nextStart>reslen)                    reslen=i-nextStart;                nextStart=dps[s[i]].loc+1;                i=nextStart-1;                for (int i=0; i<1000; ++i)                {                    dps[i].dp=false;                    dps[i].loc=-1;                }            }        }        if(i==s.size())            if(s.size()-nextStart>reslen)                reslen=s.size()-nextStart;        return reslen;    }};

 

Longest Substring Without Repeating Characters