2015年7月28日 星期二

LEET code--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.

找出連續且每個字元都不一樣的數列
一開始用爆力法,但是會超過時間....
只好去翻discuss
有人很厲害的把數列enumerate
接著每次看到一個字元,就轉成int 就進一個ASC[255]的陣列
該陣列記錄每個ASC字元 上次存在的enumerate數字多少
如果重複就把該數字的前一個位置enumerate找出來 減掉之後就是最常的長度
EX:
A  B C E  D  F  G  H  I   J    A   Z Q   W  B
1  2  3 4  5   6  7  8   9  10 11 12 13 14 15
第11的時候,去ASC[255]發現重複A在第1個位置, 把1記錄下來,現在最常的長度就是11-1=10
在第15的時候,B重複 再2的位置-->15-2=13的連續長度

想到這個真的很猛


class DemoApp {
    int lengthOfLongestSubstring(char* s) {
    int asc[255];
    if(*s == '\0')return 0;
    memset(asc,0,sizeof(asc));
    char *pos=s;
    int repeat=0;
    int count=0;
    int length=0;
    while( (*pos) != '\0' ){
        if( asc[*pos]!=0 )repeat= (  asc[*pos] > repeat ?  asc[*pos]:repeat  );
       
        asc[ *pos]=++count;
        if((count- repeat)>length )length=count- repeat;
        pos++;
    }
    length = ( length==0 ? count:length );
    return length;
    //    give the sequence number of the s,  if find out a repeat-> remember the number
    //
   
}
}


沒有留言:

張貼留言