-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBalancedBrackets.scala
47 lines (31 loc) · 949 Bytes
/
BalancedBrackets.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.io._
import scala.collection.mutable
object Solution {
val beg = List('{', '[', '(')
val ends = Map('}' -> '{', ')' -> '(', ']' -> '[')
def isBalanced(s: String): String = {
/*
O(n) Time and space, using a stack,
if we find a beggining char we push into the stack,
else we check if top is our counter char
*/
val stack = mutable.Stack[Char]()
s.foreach {
case c if beg.contains(c) => stack.push(c)
case c if stack.nonEmpty && ends(c) == stack.top => stack.pop()
case _ => return "NO"
}
if (stack.isEmpty) "YES" else "NO"
}
def main(args: Array[String]) {
val stdin = scala.io.StdIn
val printWriter = new PrintWriter(new OutputStreamWriter(System.out))
val t = stdin.readLine.trim.toInt
for (tItr <- 1 to t) {
val s = stdin.readLine
val result = isBalanced(s)
printWriter.println(result)
}
printWriter.close()
}
}