Changed implemention to a Stack instead of a List
This commit is contained in:
parent
53d3bf9794
commit
4ee707c789
2 changed files with 32 additions and 31 deletions
|
@ -1,32 +1,32 @@
|
||||||
class BracketPush {
|
import java.util.Stack
|
||||||
companion object {
|
|
||||||
fun isValid(inpString: String): Boolean{
|
class BracketPush {
|
||||||
val stack = mutableListOf<Char>()
|
companion object {
|
||||||
val realString = inpString.filter {
|
fun isValid(inpString: String): Boolean{
|
||||||
(it == '{') or
|
val stack = Stack<Char>()
|
||||||
(it == '[') or
|
val realString = inpString.filter {
|
||||||
(it == '(') or
|
(it == '{') or
|
||||||
(it == ')') or
|
(it == '[') or
|
||||||
(it == ']') or
|
(it == '(') or
|
||||||
(it == '}') }
|
(it == ')') or
|
||||||
for (i in realString){
|
(it == ']') or
|
||||||
if ((i == '{') or
|
(it == '}') }
|
||||||
(i == '[') or
|
for (i in realString){
|
||||||
(i == '(')){
|
if ((i == '{') or (i == '[') or (i == '(')){
|
||||||
stack.add(0, i)
|
stack.push(i)
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
val temp = if (stack.size == 0) {'a'} else {stack.removeAt(0)}
|
val temp = if (stack.size == 0) {'a'} else {stack.pop()}
|
||||||
when (temp){
|
when (temp){
|
||||||
'(' -> if (i != ')') return false
|
'(' -> if (i != ')') return false
|
||||||
'{' -> if (i != '}') return false
|
'{' -> if (i != '}') return false
|
||||||
'[' -> if (i != ']') return false
|
'[' -> if (i != ']') return false
|
||||||
else -> return false
|
else -> return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return stack.isEmpty()
|
return stack.isEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -23,6 +23,7 @@ class BracketPushTest(val input: String, val expectedOutput: Boolean) {
|
||||||
arrayOf("([{])", false),
|
arrayOf("([{])", false),
|
||||||
arrayOf("[({]})", false),
|
arrayOf("[({]})", false),
|
||||||
arrayOf("(((185 + 223.85) * 15) - 543)/2", true),
|
arrayOf("(((185 + 223.85) * 15) - 543)/2", true),
|
||||||
|
arrayOf("b(())[]", true),
|
||||||
arrayOf("\\\\left(\\\\begin{array}{cc} \\\\frac{1}{3} & x\\\\\\\\ \\\\mathrm{e}^{x} &... x^2 \\\\end{array}\\\\right)", true)
|
arrayOf("\\\\left(\\\\begin{array}{cc} \\\\frac{1}{3} & x\\\\\\\\ \\\\mathrm{e}^{x} &... x^2 \\\\end{array}\\\\right)", true)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue