Created
June 17, 2014 23:12
-
-
Save eckorog2005/07253e79e08d354e9e38 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* 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