[LeetCode]Longest SubString Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

思考:记录字符下标计算长度,复杂度O(n)。注意start位置。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.size() == 0) return 0;
        vector<int> flag(256, -1);
        int maxLength = 0;
        int length = 0;
        int start = 0; //子串起始位置
        for(int i = 0; i < s.size(); ++i) {
            if(flag[s[i]] != -1) {
                if(flag[s[i]] >= start) {
                    start = flag[s[i]] + 1;
                }
            }
            flag[s[i]] = i;
            length = i - start;
            if(length > maxLength) { 
                maxLength = length;
            }
        }
        return maxLength + 1;
    }
};

  

原文地址:https://www.cnblogs.com/Rosanna/p/3406591.html