Java code to Split a String into Maximum number of Balanced Strings

 


We are given a string which contains only characters 'R' and 'L'. A balanced string is one which has equal number of 'R' and 'L' characters.

The problem statement is to find the maximum number of balanced strings which can be extracted from an input String. Here is a link to the leetcode problem, and we'll try to solve it today.


/**
 * Split the String into maximum number of Balanced Strings
 * 
 * @author computengine.com
 * @param s
 * @return
 */
public int balancedStringSplit(String s) {

	int countR = 0, countL = 0, count = 0;

	// loop through the input string
	for (int i = 0; i < s.length(); i++) {

		// increment if 'R' found
		if (s.charAt(i) == 'R')
			countR++;
		// increment if 'L' found
		if (s.charAt(i) == 'L')
			countL++;
		// increment counter when Number of 'R' match Number of 'L', and reset R and L counters
		if (countR == countL) {
			count++;
			countR = 0;
			countL = 0;
		}

	}
	return count;
}


In order to solve this problem, we'll loop through the input string for its length. If character 'R' is found, we increment countR. If character 'L' is found, we increment countL. If countR becomes equal to countL, it signifies the max length for the current occurence of balanced String has been reached, and we'll increment our main counter, as well as reset R and L counters, so that we can start again. 

Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on FacebookTwitterTumblrLeetCode 

Comments

Popular posts from this blog

Calculate Your CTC Salary Hike Percentage - Online Calculator to find your New Salary

Find the Longest Streak of 1's in a Binary Array using Java Code

Java Program to Read a Properties file and return a Property Value

Create a File logging Utility using Java Code

What is my IP Address - How to find your IP address on Local Network using Command Prompt, and External Network using JavaScript Code