Skip to content

Instantly share code, notes, and snippets.

@AndreasHassing
Last active December 30, 2016 14:47
Show Gist options
  • Select an option

  • Save AndreasHassing/eecd3f9b95eb9e126cd5326dccdbc943 to your computer and use it in GitHub Desktop.

Select an option

Save AndreasHassing/eecd3f9b95eb9e126cd5326dccdbc943 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Text;
class Solution {
static void Main(String[] args) {
var t = Convert.ToInt32(Console.ReadLine());
for(var a0 = 0; a0 < t; a0++) {
var expression = Console.ReadLine();
Console.WriteLine(IsBalanced(expression) ? "YES" : "NO");
}
}
static bool IsBalanced(string expression) {
var sb = new StringBuilder(40);
foreach (var c in expression) {
if (IsClosingBracket(c)) {
if (sb.Length == 0) return false;
if (!IsClosingBracketFor(c, sb[sb.Length-1])) return false;
sb.Remove(sb.Length-1, 1);
} else {
sb.Append(c);
}
}
return sb.Length == 0;
}
static bool IsClosingBracket(char c) {
return c == '}' || c == ']' || c == ')';
}
static bool IsClosingBracketFor(char c, char other) {
return (c == '}' && other == '{')
|| (c == ']' && other == '[')
|| (c == ')' && other == '(');
}
}
@AndreasHassing
Copy link
Author

AndreasHassing commented Dec 30, 2016

Could possibly extend on the char type and give it the IsClosingBracket and IsClosingBracketFor members.

using System;
class TestCharBracketExtensions {
  public static void Main (string[] args) {
    Console.WriteLine('}'.IsClosingBracket());       // => true
    Console.WriteLine(')'.IsClosingBracketFor('(')); // => true
  }
}

public static class CharBracketExtensions {
  public static bool IsClosingBracket(this char c) {
    return c == '}' || c == ']' || c == ')';
  }
  
  public static bool IsClosingBracketFor(this char c, char other) {
    return (c == '}' && other == '{')
        || (c == ']' && other == '[')
        || (c == ')' && other == '(');
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment