1. 문제(원본)
Balanced strings are those who have equal quantity of 'L' and 'R' characters.
Given a balanced string s split it in the maximum amount of balanced strings.
Return the maximum amount of splitted balanced strings.
Example 1:
Input: s = "RLRRLLRLRL" Output: 4 Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Example 2:
Input: s = "RLLLLRRRLR" Output: 3 Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
Example 3:
Input: s = "LLLLRRRR" Output: 1 Explanation: s can be split into "LLLLRRRR".
Example 4:
Input: s = "RLRRRLLRLL" Output: 2 Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'
Constraints:
- 1 <= s.length <= 1000
- s[i] = 'L' or 'R'
2. 문제
"L"과"R"을 가진 문자열에서 L의 수와 R의 수가 밸런스 있게 나타나는 경우를 카운트한다.
3. 나의 답
class Solution {
func balancedStringSplit(_ s: String) -> Int {
var count = 0
var lCount = 0
var RCount = 0
s.forEach { (c) in
if c == "L" {
lCount += 1
} else {
RCount += 1
}
if lCount == RCount {
count += 1
lCount = 0
RCount = 0
}
}
return count
}
}
4. 다른 유저의 답
#1
func balancedStringSplit(_ s: String) -> Int {
var accumulator = 0
var currentState = 0
for leftOrRight in s {
currentState += leftOrRight == "L" ? 1 : -1
if currentState == 0 {
accumulator += 1
}
}
return accumulator
}
5. 마무리
이번 문제는 의외 어떻게 로직을 구현할까 생각을 좀 많이 했다.
푸는 데는 막힘 없이 풀어나갔지만 밸런스라는 것에 좀 생각을 했었던 것 같다.
다른 유저의 답변을 보면 대부분 비슷한 답변이었지만 + 와 -를 사용해서 1이 되었을 때 카운트한다는 것이 차이가 있었다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode1323. Maximum 69 Number (0) | 2020.03.08 |
---|---|
LeetCode1365. How Many Numbers Are Smaller Than the Current Number (0) | 2020.03.08 |
LeetCode771. Jewels and Stones (0) | 2020.02.23 |
LeetCode1351. Count Negative Numbers in a Sorted Matrix (0) | 2020.02.16 |
LeetCode1342. Number of Steps to Reduce a Number to Zero (0) | 2020.02.16 |