반응형
https://leetcode.com/problems/split-a-string-in-balanced-strings/description/
간단 구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
최소 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;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 1252. Cells with Odd Values in a Matrix (0) | 2024.01.04 |
---|---|
(C++) - LeetCode (easy) 1260. Shift 2D Grid (1) | 2024.01.03 |
(C++) - LeetCode (easy) 1207. Unique Number of Occurrences (1) | 2023.12.05 |
(C++) - LeetCode (easy) 1200. Minimum Absolute Difference (0) | 2023.12.04 |
(C++) - LeetCode (easy) 1189. Maximum Number of Balloons (1) | 2023.11.29 |