leetcode第三題:最長子串的c++9行解法


題目:

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.


解答:

//9行實現:dict用來記錄每個字母最後出現的位置
//start用來記錄每個子序列的起始。
//如果發現某個字符發生了重複,那麼我就把start記爲這個字符上一次出現的位置。

int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);             //定義一個vector叫做dict,內容是256個-1
        int maxLen = 0, start = -1;            //標尺start        
        for (int i = 0; i != s.length(); i++) {
            if (dict[s[i]] > start)            //如果字符串中的字符大於標尺
                start = dict[s[i]];            //那麼標尺刷新;
            dict[s[i]] = i;                    //把dict中對應的值改爲i(最後應該是0123456...)
            maxLen = max(maxLen, i - start);   //max記爲最大的i-標尺
        }
        return maxLen;
    }


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