본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1221. Split a String in Balanced Strings

반응형

https://leetcode.com/problems/split-a-string-in-balanced-strings/description/

 

Split a String in Balanced Strings - LeetCode

Can you solve this real interview question? Split a String in Balanced Strings - Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it into some number of substrings such that: * Each substrin

leetcode.com

간단 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

최소 substing 개수로 split할 필요 없고 R과 L개수가 같을 때마다 split해주면 되므로 간단하게 해결 가능합니다.

1. 정답 변수 ans와 'L'개수를 세줄 lcnt, 'R'개수를 세줄 rcnt를 선언 후 0으로 초기화해줍니다.

📔 풀이과정

s의 원소를 순회하며

1. R과 L개수를 세어 lcnt와 rcnt에 누적해 더해줍니다.

2. 이후 lcnt와 rcnt를 비교해 같다면 split가능하므로 ans를 1더해주며 rcnt, lcnt를 0으로 초기화해줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int balancedStringSplit(string s) {
        int ans = 0, lcnt = 0, rcnt = 0;
        for(auto c : s) {
            if(c == 'R') {
                rcnt++;
            } else {
                lcnt++;
            }
            if(rcnt == lcnt) {
                rcnt = 0;
                lcnt = 0;
                ans++;
            }
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.