SHARE
TWEET

Untitled

a guest Jul 23rd, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import scala.annotation.tailrec
  2. import scala.collection.mutable
  3.  
  4. object Solution {
  5.  
  6.   @tailrec
  7.   def foo(opened: List[Char], remaining: List[Char]): Int = {
  8.     remaining match {
  9.       case Nil => if (opened.isEmpty) 1 else 0
  10.       case h :: t =>
  11.         h match {
  12.           case '{' | '[' | '(' => foo(h :: opened, t)
  13.           case '}' | ']' | ')' =>
  14.             val opening = openingFor(h)
  15.             opened match {
  16.               case `opening` :: remainingOpened => foo(remainingOpened, t)
  17.               case _ => 0
  18.             }
  19.         }
  20.     }
  21.   }
  22.  
  23.   private def openingFor(c: Char) = c match {
  24.     case '}' => '{'
  25.     case ']' => '['
  26.     case ')' => '('
  27.   }
  28.  
  29.   def solution(s: String): Int = foo(List.empty, s.toList)
  30.  
  31.  
  32.   def solutionImperative(s: String): Int = {
  33.  
  34.     val stack = mutable.Stack[Char]()
  35.  
  36.  
  37.     for (c <- s) {
  38.       c match {
  39.         case '{' | '[' | '(' => stack.push(c)
  40.         case '}' => if (stack.pop() != '{') return 0
  41.         case ']' => if (stack.pop() != '[') return 0
  42.         case ')' => if (stack.pop() != '(') return 0
  43.       }
  44.  
  45.     }
  46.     if (stack.isEmpty) 1 else 0
  47.   }
  48.  
  49.  
  50.   def main(args: Array[String]): Unit = {
  51.     println(solution("{[()()]}"))
  52.     println(solution("([)()]"))
  53.   }
  54. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top