Skip to content

Instantly share code, notes, and snippets.

@elimence
Last active August 31, 2015 01:40
Show Gist options
  • Save elimence/9fd4d407777c82510a5c to your computer and use it in GitHub Desktop.
Save elimence/9fd4d407777c82510a5c to your computer and use it in GitHub Desktop.
Accepts a list of strings containing parentheses, and checks if they are balanced or not
import java.util.*;
public class BalanceParen {
public static void main(String[] args) {
System.out.println(isBalanced(")))))"));
}
private static boolean isBalanced(String input) {
Stack<Character> stack = new Stack<>();
Map<Character, Character> braces = new HashMap<Character, Character>() {{
put('(', ')'); put('[', ']'); put('{', '}');
}};
for(char ch : input.toCharArray()) {
if(braces.containsKey(ch)) {
stack.push(ch); // push open braces into stack
} else {
if(stack.isEmpty()) {
return false; // if we have a close brace and stack is empty, return false
}
if(ch != braces.get(stack.pop())) {
return false;
}
}
}
return stack.isEmpty();
}
}
import scala.collection.mutable.Stack
import scala.collection.immutable.HashMap
object BalanceParen {
def main(args: Array[String]) {
args map { str => println(s"$str : ${isBalanced(str)}") }
}
def isBalanced(input: String): Boolean = {
val stack = new Stack[Char]
val brace = HashMap('(' -> ')', '[' -> ']', '{' -> '}')
input map (( ch: Char ) => {
if( brace contains ch ) stack push ch
else {
if( stack.isEmpty ) return false
if( brace.get(stack.pop) != Some(ch) ) return false
}
})
return stack.isEmpty
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment