From 4ee707c789e6ba4c4c305ba43f32d3ba952d3cbf Mon Sep 17 00:00:00 2001 From: acicchetti Date: Thu, 14 Feb 2019 14:02:17 -0500 Subject: [PATCH] Changed implemention to a Stack instead of a List --- .../src/main/kotlin/BracketPush.kt | 62 +++++++++---------- .../src/test/kotlin/BracketPushTest.kt | 1 + 2 files changed, 32 insertions(+), 31 deletions(-) diff --git a/kotlin/bracket-push/src/main/kotlin/BracketPush.kt b/kotlin/bracket-push/src/main/kotlin/BracketPush.kt index c2da8bb..31e7362 100644 --- a/kotlin/bracket-push/src/main/kotlin/BracketPush.kt +++ b/kotlin/bracket-push/src/main/kotlin/BracketPush.kt @@ -1,32 +1,32 @@ -class BracketPush { - companion object { - fun isValid(inpString: String): Boolean{ - val stack = mutableListOf() - val realString = inpString.filter { - (it == '{') or - (it == '[') or - (it == '(') or - (it == ')') or - (it == ']') or - (it == '}') } - for (i in realString){ - if ((i == '{') or - (i == '[') or - (i == '(')){ - stack.add(0, i) - } - else { - val temp = if (stack.size == 0) {'a'} else {stack.removeAt(0)} - when (temp){ - '(' -> if (i != ')') return false - '{' -> if (i != '}') return false - '[' -> if (i != ']') return false - else -> return false - } - } - } - return stack.isEmpty() - } - - } +import java.util.Stack + +class BracketPush { + companion object { + fun isValid(inpString: String): Boolean{ + val stack = Stack() + val realString = inpString.filter { + (it == '{') or + (it == '[') or + (it == '(') or + (it == ')') or + (it == ']') or + (it == '}') } + for (i in realString){ + if ((i == '{') or (i == '[') or (i == '(')){ + stack.push(i) + } + else { + val temp = if (stack.size == 0) {'a'} else {stack.pop()} + when (temp){ + '(' -> if (i != ')') return false + '{' -> if (i != '}') return false + '[' -> if (i != ']') return false + else -> return false + } + } + } + return stack.isEmpty() + } + + } } \ No newline at end of file diff --git a/kotlin/bracket-push/src/test/kotlin/BracketPushTest.kt b/kotlin/bracket-push/src/test/kotlin/BracketPushTest.kt index dcaa6a6..322c27d 100644 --- a/kotlin/bracket-push/src/test/kotlin/BracketPushTest.kt +++ b/kotlin/bracket-push/src/test/kotlin/BracketPushTest.kt @@ -23,6 +23,7 @@ class BracketPushTest(val input: String, val expectedOutput: Boolean) { arrayOf("([{])", false), arrayOf("[({]})", false), 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) ) }