[
string
greedy
accumulate
]
Leetcode 1221. Split a String in Balanced Strings
Problem statement
https://leetcode.com/problems/split-a-string-in-balanced-strings/
Solution
Replace all R
with 1
and all L
with -1
, then use accumulate and calculate number of zeroes.
Complexity
It is O(n)
for time and space.
Code
class Solution:
def balancedStringSplit(self, s):
s = [1 if x == "R" else -1 for x in s]
acc = list(accumulate(s))
return acc.count(0)