3. Longest Substring Without Repeating Characters

Sunnyrain·2022년 1월 25일
0

leetcode

목록 보기
5/5

Problem

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

Approach

Simple Explanation

Why?

Code

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.empty()) return 0;
        
        unordered_set<int> charSet;
        int maxLength = -1;
        
        // with 2 pointers: p1, p2
        int i = 0, j = 0;
        
        for (; j < s.size(); ){
            // 1. p2 goes until meets the first duplicated char
            while (charSet.find(s[j]) == charSet.end() && j < s.size()) {
                charSet.insert(s[j]);
                j++;
            }
            
            maxLength = max(maxLength, j - i);
            
            // 2. p1 goes until removes the duplicated char
            while (charSet.find(s[j]) != charSet.end() && i <= j) {
                charSet.erase(s[i]);
                i++;
            }
        }
        return maxLength;
    }
};

Complexity

1) Time

2) Space

profile
sunny and rainy at the same time

0개의 댓글