Skip to main content
Back to problems
#1221
Easy Algorithms

Split a string in balanced strings

String Greedy Counting
87.3% acceptance
Feb 25, 2026
2905
957
Balanced strings are those that have an equal quantity of 'L' and 'R' characters. Given a balanced string s, split it into some number of substrings such that: Each substring is balanced. Return the maximum number of balanced strings you can obtain.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn balanced_string_split(s: String) -> i32 {
    let mut balance = 0i32;
    let mut count = 0;
    for c in s.chars() {
      if c == 'R' { balance += 1; } else { balance -= 1; }
      if balance == 0 { count += 1; }
    }
    count
  }
}