Balanced strings are those who have 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 splitted balanced strings.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Example 2:
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
Constraints:
1 <= s.length <= 1000
s[i] = 'L' or 'R'
Solution : in this problem if character == L so increment l and if its R so increment r, so then check if both are not equal to 0 and l == r so increment result because here first match has found, and assign l =0, r=0(reset to 0).
class Solution {
public int balancedStringSplit(String s) {
int l = 0;
int r =0;
int result = 0;
for(int i=0;i<s.length();i++){
if(s.charAt(i) == 'L'){
l++;
}else if(s.charAt(i) == 'R'){
r++;
}
if(l != 0 && r != 0 && l ==r){
result++;
l=0;
r=0;
}
}
return result;
}
}
Given a balanced string s split it in the maximum amount of balanced strings.
Return the maximum amount of splitted balanced strings.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Example 2:
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
Constraints:
1 <= s.length <= 1000
s[i] = 'L' or 'R'
Solution : in this problem if character == L so increment l and if its R so increment r, so then check if both are not equal to 0 and l == r so increment result because here first match has found, and assign l =0, r=0(reset to 0).
class Solution {
public int balancedStringSplit(String s) {
int l = 0;
int r =0;
int result = 0;
for(int i=0;i<s.length();i++){
if(s.charAt(i) == 'L'){
l++;
}else if(s.charAt(i) == 'R'){
r++;
}
if(l != 0 && r != 0 && l ==r){
result++;
l=0;
r=0;
}
}
return result;
}
}