Split String into Balanced Strings | String Problem
4 years ago Lalit Bhagtani 0
Problem Statement
You have given a balanced string S, split it into the maximum amount of balanced strings.
Note :- Balanced strings are the strings, which have an equal number of “A” and “B” characters.
Example
Input :- S = "ABAABBABAB" Output :- 4
Input :- S = "ABAABBABABBBAAAB" Output :- 6
Solution
Traverse the input string after converting it into character array. At each iteration, check if character is ‘A‘ or ‘B‘. If character is ‘A‘ increase its count by 1 and if character is ‘B‘ increase its count by 1. When both ‘A‘ and ‘B‘ count is equal, then increase the result count by 1 and make ‘A‘ and ‘B‘ count to zero.
Program
public class Main { public static void main(String[] args) { Main main = new Main(); int result = main.balancedStringSplit("ABAABBABABBBAAAB"); System.out.println(result); } /* Solution */ public int balancedStringSplit(String s) { char[] chars = s.toCharArray(); int A = 0, B = 0, count = 0; for(int i=0; i<chars.length; i++){ if(chars[i] == 'A') A++; if(chars[i] == 'B') B++; if(A == B){ A = 0; B = 0; count++; } } return count; } }
Result
6
Similar Post
That’s all for Split String into Balanced Strings in Java, If you liked it, please share your thoughts in a comments section and share it with others too.