algorithm - Scala code to check if parenthesis are balanced -
i'm writing scala function check balanced parentheses. "()","([]{})"
both balanced, ")","(){[}]"
aren't balanced
below code wrote should working. have no idea why say's false inputs try.
package general import scala.collection.mutable.stack import scala.collection.immutable.hashmap object balanceparen { def main(args: array[string]) { print(isbalanced("()")); } 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( brace.isempty ) return false if( brace.get(stack.pop) != ch ) return false } }) return stack.isempty } }
hashmap
's get
method returns option
, test needs change like:
if( brace.get(stack.pop) != some(ch) ) return false
or:
if( brace.get(stack.pop).contains(ch) ) return false
Comments
Post a Comment