Longest Substring with At Most Two Distinct Characters

유승선 ·2024년 2월 16일
0

LeetCode

목록 보기
105/115

sliding window 문제에는 항상 비슷한 유형의 코드를 사용하는데 보통 문제가 최소, 최대의 구간을 물어본다. 여기서 중요한거는 조건에 맞는 부분일때는 꼭 변수에 저장해주고,

초과되는 부분이 있다면 다른 while 룹을 사용해서 내가 탐색하고자 하는 부분의 범위를 계속해서 좁혀주는게 가장 중요하다.

옛날에 프로그래머스 같은 곳에 보석 문제가 생각나기도 하였다.

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        map<char,int> hashMap; 
        int left = 0, right = 0; 
        int answer = 0; 
        while(right < s.length()){
            hashMap[s[right]]++; 
            if(hashMap.size() <= 2) answer = max(answer, right - left + 1); 
            while(hashMap.size() > 2){
                
                hashMap[s[left]]--;
                if(hashMap[s[left]] <= 0) hashMap.erase(s[left]); 
                left++; 
            }



            right++; 
        }
        return answer; 
    }
};
profile
성장하는 사람

0개의 댓글