Longest Substring Without Repeating Characters 字串中最長的無重複子串長度,longestrepeating

來源:互聯網
上載者:User

Longest Substring Without Repeating Characters 字串中最長的無重複子串長度,longestrepeating

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.


題目的意思是求字串中最長的無重複子串長度,如上面的  abcabcbb    最長無重複子串為abc  長度為3

直接暴力法:代碼如下

class Solution {public:    int lengthOfLongestSubstring(string s) {               int i,j,temp,result=1;                for(i=0;i<s.length();i++)        {            temp=1;            for(j=0;j<s.length()-i;j++)            {                if(check(s,i,j))                    temp++;                else                    continue;            }                        result=max(result,temp);        }                return result;            }    bool check(string s,int i,int j)    {        char ch=s[j];                for(int t=i;t<j;t++)        {            if(ch==s[t])            {                return false;            }        }        return true;}};

暴力法雖然簡單,但時間過不了,下面用一個複雜度為n的演算法


思路:

用一個256位元組asc[](字元共有256個,包括128個擴充字元),字串中每一個字元的ASCII值對應該字元在數組中的位置

如字元a  在   asc[a]中的下標為97

初始化數組asc,令每一個元素為-1。定義start,start表示每次無重複字串的其實點,初始值為0.從i=0開始遍曆字串,如果數組asc中沒有出現該字元(asc[ch]==-1),那麼令asc[ch]==i,記錄下來該字元在字串中的位置,接著遍曆,如果遇到asc[ch]!=-1表示該字元已經出現了,需要將start到j的asc數組中的元素抹掉。然後重設start,令start=max(asc[i]+1,start);然後將

最後結果為   result=max(result,i-start);

代碼如下:

<span style="font-size:18px;">class Solution {public:    int lengthOfLongestSubstring(string s) {                               int result=0;        int a[128];        int i,j,t,start=0;                for(i=0;i<128;i++)            a[i]=-1;                    for(i=0;i<s.length();i++)        {                        if(a[s[i]]!=-1)            {               if(result<i-start)                    result=i-start;                                    for(j=start;j<a[s[i]];j++)                    a[j]=-1;                start=max(start,a[s[i]]+1);              //  result=max(result,i-start);            }                        a[s[i]]=i;                    }        result=max(result,i-start);        return result;            }};</span>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.