Balanced Strings

CSharp · Console

/Program.cs

using System;
using System.Text.RegularExpressions;
					
public class Program
{
	public static void Main()
	{
		string s = "RLRRLLRLRL";
		Console.WriteLine($"Output: {BalancedString(s)}");
	}
	
	// Assuming there can be only 'L' and 'R' in the string
	static int BalancedString(string s) {
		CheckBalancedString(s);
		
		int count = 0;
		
		for(int i=0; i< s.Length - 1;i++){
			if (!s[i].Equals(s[i+1])) {
				count++;
				i++; // Next index is part of the set hence he hop it.
			}
		}
		
		return count;
	}
	
	static void CheckBalancedString(string s){
		Regex r = new Regex("^[LR]*$");
		if (!r.IsMatch(s)) throw new Exception("Sentence can only be made of 'L' and 'R' characters.");
		else Console.WriteLine($"{s} matches the expression.");
		
	}
}
;