# LC 1221. Split a String in Balanced Strings
### [Problem link](https://leetcode.com/problems/split-a-string-in-balanced-strings/)
###### tags: `leedcode` `python` `c++` `easy` `Greedy`
**Balanced** strings are those that have an equal quantity of <code>'L'</code> and <code>'R'</code> characters.
Given a **balanced** string <code>s</code>, split it into some number of substrings such that:
- Each substring is balanced.
Return the **maximum** number of balanced strings you can obtain.
**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 = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'.
Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2<sup>nd</sup> and 5<sup>th</sup> substrings are not balanced.
```
**Example 3:**
```
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
```
**Constraints:**
- <code>2 <= s.length <= 1000</code>
- <code>s[i]</code> is either <code>'L'</code> or <code>'R'</code>.
- <code>s</code> is a **balanced** string.
## Solution 1 - Greedy
#### Python
```python=
class Solution:
def balancedStringSplit(self, s: str) -> int:
cnt = 0
res = 0
for c in s:
if c == 'R':
cnt += 1
else:
cnt -= 1
if cnt == 0:
res += 1
return res
```
#### C++
```cpp=
class Solution {
public:
int balancedStringSplit(string s) {
int res = 0;
int cnt = 0;
for (char& c: s) {
if (c == 'R') {
cnt++;
} else {
cnt--;
}
if (cnt == 0) {
res++;
}
}
return res;
}
};
```
>### Complexity
>| | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1 | O(n) | O(1) |
## Note
x