Longest Substring Without Repeating Characters-----LeetCode

題目

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.

分析

說到底就是找一個沒有重複字符的連續子串的長度。
思路是依次掃描字符串,用一個數組存儲每個字符最近一次出現的位置,噹噹前位置的字符已經出現過了,那麼子串長度爲當前位置減去最近一次出現的位置。

代碼

這個題思路並不難,不過發現一個代碼寫得很精簡,記錄一下:

以下是我的代碼

// 寫得並不精簡
int lengthOfLongestSubstring(char* s) {
    int len = strlen(s);
    int max = 0;
    int ans = 0;
    int sp = 0;
    int pos[300];
    for(int i=0;i<300;i++){
        pos[i] = -1;
    }
    for(int i = 0;i<len+1;i++){
        ans++;
        if(i==len){
            max = ans-1>max?ans-1:max;
            break;
        }
        char c = s[i];
        if(pos[c]!=-1 && pos[c]!=i && pos[c]>=sp){
            int t = pos[c];
            pos[c] = i;
            max = ans-1>max?ans-1:max;
            i = t;
            sp = t+1;
            ans = 0;
        }else{
            pos[c] = i;
        }
    }
    return max;
}

這個是別人的代碼,代碼很巧妙
http://www.cnblogs.com/dollarzhaole/p/3155712.html

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int locs[256];//保存字符上一次出現的位置
        memset(locs, -1, sizeof(locs));

        int idx = -1, max = 0;//idx爲當前子串的開始位置-1
        for (int i = 0; i < s.size(); i++)
        {
            if (locs[s[i]] > idx)//如果當前字符出現過,那麼當前子串的起始位置爲這個字符上一次出現的位置+1
            {
                idx = locs[s[i]];
            }

            if (i - idx > max)
            {
                max = i - idx;
            }

            locs[s[i]] = i;
        }
        return max;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章