본문 바로가기
IT/알고리즘

14] Leetcode 1221. Split a String in Balanced Strings

by 깻잎쌈 2020. 6. 25.
반응형
 

Split a String in Balanced Strings - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

R과 L로 구성된 문자열을 R과 L의 개수가 똑같은 문자열로 나누려고 한다. 

가장 많이 쪼갰을 때 그 숫자를 리턴하는 문제.

살짝 헷갈릴 수도 있지만 

그냥 앞에서부터 R, L 개수를 각각 세면서 둘이 같아질 때를 리턴하면 된다.

class Solution {
public:
    int balancedStringSplit(string s) {
        int ans= 0;
        int cntR= 0;
        int cntL= 0;
        for(int i = 0;i<s.size();i++){
            if(s[i]=='R'){
                cntR++;
                if(cntR == cntL)
                    ans++;
            }      
            else{
                cntL++;
                if(cntR == cntL)
                    ans++;
            }               
            
        }
        return ans;          
            
    }
};
반응형

댓글