Split a String in Balanced Strings

easy string greedy counter

Problem

A string is balanced if it has an equal number of 'L' and 'R' characters. Given a balanced string s, split it into the maximum number of balanced substrings and return that count.

Inputs = "RLRRLLRLRL"
Output4
Splits into "RL", "RRLL", "RL", "RL", each with equal L and R.

def balanced_string_split(s):
    count = 0
    balance = 0
    for c in s:
        balance += 1 if c == 'L' else -1
        if balance == 0:
            count += 1
    return count
function balancedStringSplit(s) {
  let count = 0;
  let balance = 0;
  for (const c of s) {
    balance += c === 'L' ? 1 : -1;
    if (balance === 0) count++;
  }
  return count;
}
class Solution {
    public int balancedStringSplit(String s) {
        int count = 0;
        int balance = 0;
        for (char c : s.toCharArray()) {
            balance += (c == 'L') ? 1 : -1;
            if (balance == 0) count++;
        }
        return count;
    }
}
int balancedStringSplit(string s) {
    int count = 0;
    int balance = 0;
    for (char c : s) {
        balance += (c == 'L') ? 1 : -1;
        if (balance == 0) count++;
    }
    return count;
}
Time: O(n) Space: O(1)