@@ -14,9 +14,6 @@ import scala.collection.mutable.Stack
14
14
*/
15
15
object Solution {
16
16
17
- val OpenToClose : Map [Char , Char ] = Map ('{' -> '}' , '[' -> ']' , '(' -> ')' )
18
- val CloseToOpen : Map [Char , Char ] = OpenToClose .map(_.swap)
19
-
20
17
def main (args : Array [String ]): Unit = {
21
18
println(! isValid(" [" ))
22
19
println(isValid(" ()[]{}" )) // all should be true
@@ -31,63 +28,22 @@ object Solution {
31
28
}
32
29
33
30
def isValid (s : String ): Boolean = {
34
- stackParenthesisSolution(s) // Stack Solution
35
- // parenthesesAreBalanced(s) // Tail recursion solution
36
- }
37
-
38
- import scala .collection .mutable .Stack
39
- /**
40
- * Stack solution
41
- */
42
- def stackParenthesisSolution (s : String ): Boolean = {
31
+ import scala .collection .mutable .Stack
43
32
val stack = new Stack [Char ]()
44
- if (s.size == 0 ) stack.push( 'f ' )
45
-
46
- s.foreach (char => {
33
+ val OpenToClose : Map [ Char , Char ] = Map ( '{' -> '}' , '[' -> ']' , '(' -> ') ' )
34
+
35
+ def checkPar (char : Char ) : Boolean = {
47
36
if (OpenToClose .contains(char)) {
48
37
stack.push(char)
38
+ true
39
+ } else if (stack.size > 0 && OpenToClose .get(stack.top) == Some (char)) {
40
+ stack.pop()
41
+ true
49
42
} else {
50
- if (stack.size > 0 && OpenToClose .get(stack.top) == Some (char))
51
- stack.pop()
52
- else
53
- stack.push('f' )
54
- }
55
- })
56
-
57
- stack.size == 0
58
- }
59
-
60
- /**
61
- * Tail recursion solution
62
- * is taken from https://www.scala-algorithms.com/ParenthesesTailRecursive/
63
- *
64
- * @param
65
- * @return
66
- */
67
- def parenthesesAreBalanced (s : String ): Boolean = {
68
- if (s.isEmpty) true
69
- else {
70
- @ scala.annotation.tailrec
71
- def go (position : Int , stack : List [Char ]): Boolean = {
72
- if (position == s.length) stack.isEmpty
73
- else {
74
- val char = s(position)
75
- val isOpening = OpenToClose .contains(char)
76
- val isClosing = CloseToOpen .contains(char)
77
- if (isOpening) go(position + 1 , char :: stack)
78
- else if (isClosing) {
79
- val expectedCharForMatching = CloseToOpen (char)
80
- stack match {
81
- case `expectedCharForMatching` :: rest =>
82
- go(position + 1 , rest)
83
- case _ =>
84
- false
85
- }
86
- } else false
87
- }
43
+ false
88
44
}
89
-
90
- go(position = 0 , stack = List .empty)
91
45
}
46
+
47
+ s.size > 0 && s.forall(checkPar) && stack.size == 0
92
48
}
93
49
}
0 commit comments