[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.

 

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int len = s.size();
        int i = 0, j = 1;
        int res = 0;
        int cnt[256] = {0};
        if (len == 0) return 0;
        cnt[s[i]] ++;
        res = 1;
        while (i < j && j < len) {
            if (cnt[s[j]] == 0) cnt[s[j++]]++;
            else {
                if (j - i > res) res = j - i;
                while (cnt[s[j]] > 0) cnt[s[i++]]--;
                cnt[s[j++]]++;
            }
        } 
        if (j == len && j - i > res) res = j - i;
        return res;
    }
};

 

你可能感兴趣的:(substring)