Skip to content

Instantly share code, notes, and snippets.

@JunJaBoy
Created April 26, 2024 14:00
Show Gist options
  • Save JunJaBoy/2173a8dadfa18803b3647fb9bf67d54a to your computer and use it in GitHub Desktop.
Save JunJaBoy/2173a8dadfa18803b3647fb9bf67d54a to your computer and use it in GitHub Desktop.
HackerRank/Algorithm/BalancedBrackets kotlin
import java.util.*
const val RESULT_YES = "YES"
const val RESULT_NO = "NO"
fun isBalanced(s: String): String {
val stack = Stack<Char>()
s.forEach { char ->
when (char) {
'[' -> stack.push(']')
'{' -> stack.push('}')
'(' -> stack.push(')')
else -> {
if (stack.isEmpty() || stack.pop() != char) {
return RESULT_NO
}
}
}
}
return if (stack.isEmpty()) {
RESULT_YES
} else {
RESULT_NO
}
}
fun main(args: Array<String>) {
repeat(readln().toInt()) {
println(isBalanced(readln()))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment