Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function balanced($string) {
- return isBalanced($string, "");
- }
- function isBalanced($chars, $stack) {
- if (!strlen($chars))
- return empty($stack);
- switch ($chars[0]) {
- case '(':
- // prepend stack with '(', move to next character
- return isBalanced(substr($chars, 1), $chars[0] . $stack);
- case ')':
- // if '(' seen previously, shift stack, move to next character
- return !empty($stack) && isBalanced(substr($chars, 1), substr($stack, 1));
- default:
- // do nothing to stack, move to next character
- return isBalanced(substr($chars, 1), $stack);
- }
- }
- object Main {
- def balance(chars: List[Char]): Boolean = {
- def balanced(chars: List[Char], stack: String): Boolean = {
- if (chars.isEmpty)
- stack.isEmpty
- else if (chars.head == ')')
- balanced(chars.tail, chars.head + stack)
- else if (chars.head == '(')
- !stack.isEmpty && balanced(chars.tail, stack.tail)
- else
- balanced(chars.tail, stack)
- }
- balanced(chars, "")
- }
- }
- balance("(if (0) false (x))".toList) - fails
- balance("profit and loss (P&L).n(cashflow)".toList) - fails
- balance(":)".toList) - passes
- balance(")(()".toList) - passes
- def balance(chars: List[Char]): Boolean = {
- @tailrec def balanced(chars: List[Char], open: Int): Boolean =
- chars match {
- case Nil => open == 0
- case '(' :: t => balanced(t, open + 1)
- case ')' :: t => open > 0 && balanced(t, open - 1)
- case _ :: t => balanced(t, open)
- }
- balanced(chars, 0)
- }
- def balance(chars: List[Char]): Boolean = chars.foldLeft(0){
- case (0, ')') => return false
- case (x, ')') => x - 1
- case (x, '(') => x + 1
- case (x, _ ) => x
- } == 0
- def balance(chars: List[Char]): Boolean =
- doBalance(chars, 0) == 0;
- def doBalance(chars: List[Char], parenthesisOpenCount: Int): Int =
- if(parenthesisOpenCount <0) -100;
- else
- if(chars.isEmpty) parenthesisOpenCount
- else
- chars.head match {
- case '(' => return doBalance(chars.tail, parenthesisOpenCount+1)
- case ')' => return doBalance(chars.tail, parenthesisOpenCount-1)
- case _ => return doBalance(chars.tail, parenthesisOpenCount)
- }
Add Comment
Please, Sign In to add comment