Last active
August 29, 2015 14:07
-
-
Save HDegano/ec9dace53596ca557135 to your computer and use it in GitHub Desktop.
Check if the parenthesis/brackets are balanced
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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