Leetcode 1221. Split a String in Balanced Strings
Leetcode Problem 1221: Split a String in Balanced Strings
You are given a string s
of ‘L’ and ‘R’ characters, and you need to split this string into as many balanced strings as possible.
A balanced string is defined as a string with an equal number of ‘L’ and ‘R’ characters.
Return the maximum number of balanced strings you can obtain.
To solve this problem, we can use a greedy approach where we count ‘L’ and ‘R’ characters as we traverse the string:
balance
) and another counter for the number of balanced strings (num_balanced
).balance
by 1 for ‘L’ and decrement it by 1 for ‘R’.balance
becomes zero, it means we have found a balanced string.#include <iostream>
#include <string>
int balancedStringSplit(std::string s) {
int balance = 0;
int num_balanced = 0;
for (char c : s) {
if (c == 'L') {
balance++;
} else if (c == 'R') {
balance--;
}
if (balance == 0) {
num_balanced++;
}
}
return num_balanced;
}
int main() {
std::string s = "RLRRLLRLRL";
std::cout << balancedStringSplit(s) << std::endl; // Output: 4
return 0;
}
Time Complexity: O(n), where n
is the length of the string s
. We traverse the string once, making the operations linear in terms of the number of characters.
Space Complexity: O(1), The space used does not scale with the input size, as we only use a few integer variables.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?