Hello!
It's day 21 of my coding diary. Yesterday, vercel was having some issues with their build system. Well, it's up and working smooth now. Let's directly move to the problem of the day.
Problem of the day - Split a String in Balanced Strings
Tag - Easy
Balanced strings are those that have an equal quantity of 'L'
and 'R'
characters.
Given a balanced string s
, split it in the maximum amount of balanced strings.
Return the maximum amount of split balanced strings.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
This is the worst problem statement, I have ever seen. It's really confusing man, all the example test cases are not clear. I spent time unnecessarily, building some dynamic programming logic for this dumb question.
So, the problem says, to find the maximum amount of split balanced strings. It does not clearly talk about the order of L
& R
.
Mentioning `splitting gives an idea of considering one sub-string having multiple balanced sub-strings as one only. but still, initially, I got confused with logic for considering all corner cases.
It turned out to be the simplest problem with just tracking count of L
& R
, that's it.
Here is my solution
`cpp
class Solution {
public:
int balancedStringSplit(string s) {
int res = 0;
int balance = 0;
for(int i=0;i<s.length();i++) {
balance += s[i] == 'L' ? 1 : -1;
if(balance == 0) res++;
}
return res;
}
};
`
Not to mention, run time 0ms and faster than 100%. Honestly, I am not happy. Such uncleared problems make me less excited about solving more problems.
Well, I will try some good medium problems tomorrow!
Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to reach out.
You might like previous editions of my coding diary
- Day #20 - To Lower Case.
- Day #19 - N-Repeated Element in Size 2N Array.
- Day #18 - Count Negative Numbers in a Sorted Matrix.
- Day #17 - Sum of Unique Elements.
- Day #16 - Best Time to Buy and Sell Stock.
- Day #15 - Count Number of Pairs With Absolute Difference K.
- Day #14 - Minimum Number of Operations to Move All Balls to Each Box.
Top comments (2)
Hi,
Just talking markdown formatting you should surround snippets with three consecutive backticks. This is why your display is messed up.
ex:
AFAIK you cannot syntax color inline code (i.e. code within a sentence). So the most you can do it put that piece of code between single backticks.
ex:
This sentence mention the
public
keyword as inline code. Just surround keywords or expressions such asforeach (item in collection)
in single backticks.Talking about your challenge, I'm not sure to understand it too much.
Based on the given example I get to that value in another fashion.
Given your string
RLRRLLRLRL
I would split it that way which also gives 4.Regards.
I did solve that problem my way with C#.
Here is the code:
I put a link to that .NET Fiddle to play around.