Home LeetCode - 1221. Split a String in Balanced Strings
Post
Cancel

LeetCode - 1221. Split a String in Balanced Strings

1221. Split a String in Balanced Strings - easy

문제

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.

제한사항

입출력 예

1
2
3
4
5
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'.
1
2
3
4
5
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'.
1
2
3
4
5
Example 3:

Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
1
2
3
4
5
6
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'

풀이

  • Hash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func balancedStringSplit(s string) int {
    var m = make(map[rune]int)
    var count = 0
    
    for _, v := range s {
        m[v]++
        
        if m['L'] == m['R'] {
            count++
        }
    }
    
    return count
}
This post is licensed under CC BY 4.0 by the author.