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.

 

贪心

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        
        vector<int> last(256, -1); //字符上次出现的位置
        int start = 0;// 子串的起始位置
        int res = 0;
        
        for(int i = 0; i<s.size(); i++)
        {
            if(last[s[i]]>=start)//之前出现过
            {
                res = max(res, i-start);
                start = last[s[i]] + 1;
            }
            last[s[i]] = i;
        }
        
        return max((int)s.size() - start, res); //最后一个字母
    }
};

 

posted @ 2017-12-13 16:08  Tycit  阅读(71)  评论(0)    收藏  举报