Leetcode#3 Longest Substring Without Repeating Characters

less than 1 minute read

Published:

https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

Idea:

Sliding window

Solution:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int map[256];
        for(int i = 0; i<256; i++)
            map[i] = -1;
        int left = 0, max = 0;
        for (int i=0; i<s.size();i++) {
            if(map[s[i]] < left) {
                max = (i-left +1 > max) ? i-left+1 : max;
            }else{
                left = map[s[i]]+1;
            }
            map[s[i]] = i;
        }
        return max;
    }
};