LeetCode Algorithms 3. Longest Substring Without Repeating Characters

題目難度: Medium


原題描述:

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.


題目大意:

        給你一個字符串,找出其不含相同字符的最長子串。


解題思路:

        用指針i從前往後掃描字符串,用一個index數組記錄每一個字符最後一次出現在原字符串中的下標,沒有出現過的爲-1,index數組的下標爲每一個字符的ASCII碼。max記錄當前不含相同字符的最長子串的長度,指針j記錄當前子串的起始位置。當第一次遇到某個字符時,將這個字符對應的index數組的值改爲字符串的當前下標;當再次遇到某個字符時,i-j即爲當前最長子串的長度,用此值和max比較並更新max,此外還要將j值更新爲重複字符在第一次出現時的後一位置,並將此位置之前的字符的index數組的值置爲-1。最後將重複字符對應的index數組的值更新。


時間複雜度分析:

        由於指針i和j都是掃描字符串一遍,因此總的時間複雜度爲O(n),n爲字符串的長度。


以下是代碼:

int getMax(int a , int b)
{
    return a>b ? a : b;
}

int lengthOfLongestSubstring(char* s)
{
    int i,j,k,m;
    int index[200];
    int ans = 0;
    memset(index,-1,sizeof(index));
    for(i=0,j=0 ; s[i]!='\0' ; ++i)
    {
        if( index[s[i]]==-1 )
        {
            index[s[i]] = i;
        }
        else
        {
            ans = getMax(ans,(i-j));
            m = j;
            j = index[s[i]] + 1;
            for(k=m ; k<j ; ++k)
                index[s[k]] = -1;
            index[s[i]] = i;
        }
    }
    ans = getMax(ans,(i-j));
    return ans;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章