Hi i have an string array that contains values as "{[()]}", "}[]{", "{()[]". Now i have to balance the braces like for each starting brace e.g. { or [ or (, there has to be a closing brace. If the input string has the same number of opening and closing braces, then the output is "YES" else "NO". Also if the string has a closing brace before a matching opening brace then also the output will be "NO". So basically the output has to be a string array that will contain the values like this for the above input string array : "YES", "NO", "NO".
I wrote the following program which has a lot of if-else condition. I was wondering if there is any better way in C# to deal with this problem.
static void Main(string[] args)
{
string[] arrBraces = Console.ReadLine().Split(' ');
string[] result = new String[arrBraces.Length];
for (int i = 0; i < arrBraces.Length; i++) {
Console.WriteLine(arrBraces[i]);
int curly = 0, square = 0, round = 0;
foreach (char c in arrBraces[i]) {
if (c == '{') {
curly++;
} else if (c == '[') {
square++;
} else if (c == '(') {
round++;
} else if (c == '}') {
if (curly > 0) {
curly--;
} else {
curly = -1;
break;
}
} else if (c == ']') {
if (square > 0) {
square--;
} else {
square = -1;
break;
}
} else if (c == ')') {
if (round > 0) {
round--;
} else {
round = -1;
break;
}
}
}
if (curly == 0 && square == 0 && round == 0) {
result[i] = "YES";
} else {
result[i] = "NO";
}
}
foreach (string str in result) {
Console.WriteLine (str);
}
Console.ReadKey();
}
I found a similar question here but seems like it is also doing the same thing, just that it is using stack to store the parenthesis whereas my problem explicitly states that the braces are in a string array.
Anyways any help or suggestions to improve the code would be appreciated.