Skip to content

Instantly share code, notes, and snippets.

@HDegano
Last active August 29, 2015 14:07
Show Gist options
  • Save HDegano/ec9dace53596ca557135 to your computer and use it in GitHub Desktop.
Save HDegano/ec9dace53596ca557135 to your computer and use it in GitHub Desktop.
Check if the parenthesis/brackets are balanced
public static bool balanced_brackets(string S)
{
var open = new List<char>(){'(', '{', '['};
var stack = new Stack<char>();
foreach (var i in S)
{
if (open.Contains(i)) stack.Push(i);
else
{
if (stack.Count == 0) return false;
bool valid = true;
switch (i)
{
case ')':
if (stack.Peek() != '(') valid = false;
break;
case '}':
if (stack.Peek() != '{') valid = false;
break;
case ']':
if (stack.Peek() != '[') valid = false;
break;
}
if (valid) stack.Pop();
else return false;
}
}
return stack.Count == 0;
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0 ; i < s.length(); i++){
char c = s.charAt(i);
if(c == '(' || c == '{' || c == '[') stack.push(c);
else {
if(stack.size() == 0) return false;
boolean valid = true;
switch (c)
{
case ')':
if (stack.peek() != '(') valid = false;
break;
case '}':
if (stack.peek() != '{') valid = false;
break;
case ']':
if (stack.peek() != '[') valid = false;
break;
}
if (valid) stack.pop();
else return false;
}
}
return stack.isEmpty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment