Leetcode 1221. Split a String in Balanced Strings
You are given a string s of lowercase English letters. A string is called balanced if it contains an equal number of ‘L’ and ‘R’ characters.
Your task is to determine the maximum number of balanced substrings that can be obtained from the given string s. You need to return the count of these substrings.
s will always be a valid and non-empty string of lowercase English letters.To solve the problem, you can use a counter to keep track of the balance between ‘L’ and ‘R’:
balance and count to 0.balance counter by 1 for ‘L’.balance counter by 1 for ‘R’.balance is 0, it means we have found a balanced substring.count of balanced substrings whenever balance is 0.count after iterating through the string.public class Solution {
public int balancedStringSplit(String s) {
int balance = 0;
int count = 0;
for (char c : s.toCharArray()) {
if (c == 'L') {
balance++;
} else {
balance--;
}
if (balance == 0) {
count++;
}
}
return count;
}
}
n is the length of the string s.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?