[LeetCode]3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

題意:

給定一個字符串,找出最長的無重複的連續字串。就比如"pwwkew"的最長無重複連續字串是"wke"。


最易想到的方法就是字符串逐一開始查找,第一個字符串找到最長的字串,依次找出,取最大值即可。

由於有256個字符,故定義了個257長度的數組,足以存下所有字符。


思路

1)定義字符數組,並把256個的值都置爲零。

2)逐個查找字符,如果未出現過,即把該下標對應的數組值置爲一。若該下標值已經是一了,則返回,

3)重置全部數組元素元素爲零,從下個下標開始繼續查找不重複字串。

4)返回最大字串長度即可。


#define CHARACTERS 257

int lengthOfLongestSubstring(char* s) 
{
    if ( !s )
    {   
        return 0;
    }
    
    int character[CHARACTERS] = { 0 };
    int len = strlen(s);
    
    int cnt  = 0;
    int size = 0;
    int maxLen = 0;
    int index = 0;
    for ( index = 0; index < len; index++ )
    {
        size = 0;
        for ( cnt = 0; cnt < CHARACTERS; cnt++ )
        {
            character[cnt] = 0;
        }
        
        for ( cnt = index; cnt < len; cnt++ )
        {
            /* pwwkew */
            int value = *(s + cnt);
            if ( character[value] == 0 )
            {
                size += 1;
                character[value] = 1;
            }
            else
            {
                break;
            }
        }
        
        if ( size > maxLen )
        {
            maxLen = size;
        }
    }
    
    return maxLen;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章