Last active
August 31, 2015 01:40
-
-
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
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
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(); | |
} | |
} |
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
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