Skip to content

Commit e56e94d

Browse files
author
tumanob
committed
Update solution scala for "20 Valid Parentheses"
1 parent 43f48ab commit e56e94d

File tree

1 file changed

+11
-55
lines changed

1 file changed

+11
-55
lines changed

ScalaSolutions/src/main/scala/ValidParentheses_p20/Solution.scala

+11-55
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,6 @@ import scala.collection.mutable.Stack
1414
*/
1515
object Solution {
1616

17-
val OpenToClose: Map[Char, Char] = Map('{' -> '}', '[' -> ']', '(' -> ')')
18-
val CloseToOpen: Map[Char, Char] = OpenToClose.map(_.swap)
19-
2017
def main(args: Array[String]): Unit = {
2118
println(!isValid("["))
2219
println(isValid("()[]{}")) // all should be true
@@ -31,63 +28,22 @@ object Solution {
3128
}
3229

3330
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
4332
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 = {
4736
if (OpenToClose.contains(char)) {
4837
stack.push(char)
38+
true
39+
} else if (stack.size > 0 && OpenToClose.get(stack.top) == Some(char)) {
40+
stack.pop()
41+
true
4942
} 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
8844
}
89-
90-
go(position = 0, stack = List.empty)
9145
}
46+
47+
s.size > 0 && s.forall(checkPar) && stack.size == 0
9248
}
9349
}

0 commit comments

Comments
 (0)