Skip to content

Commit 25c0def

Browse files
authored
Create BalancedBrackets.scala
1 parent 75bdc90 commit 25c0def

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

BalancedBrackets.scala

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

0 commit comments

Comments
 (0)