Skip to content

Instantly share code, notes, and snippets.

@eckorog2005
Created June 17, 2014 23:12
Show Gist options
  • Save eckorog2005/07253e79e08d354e9e38 to your computer and use it in GitHub Desktop.
Save eckorog2005/07253e79e08d354e9e38 to your computer and use it in GitHub Desktop.
import scala.collection.mutable
/**
* Created by roger on 6/17/14.
*/
object Solution {
val stack = mutable.Stack[Character]()
def main(args: Array[String]) {
if(isBalanced(readLine()))
println("True")
else
println("False")
}
def isBalanced(str: String):Boolean= {
var string = str
var flag = true
while(string.length > 0 && flag){
val ch = string.charAt(0)
ch match {
case '{' | '(' | '[' =>
stack.push(ch)
case '}' =>
flag = compareChar('{')
case ')' =>
flag = compareChar('(')
case ']' =>
flag = compareChar('[')
case _ =>
//ignore
}
string = string.drop(1)
}
if(stack.isEmpty){
flag
}else{
false
}
}
def compareChar(delimiter:Char):Boolean={
if (stack.isEmpty) {
false
} else if (stack.pop() != delimiter) {
false
}else{
true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment