Created
April 26, 2024 14:00
-
-
Save JunJaBoy/2173a8dadfa18803b3647fb9bf67d54a to your computer and use it in GitHub Desktop.
HackerRank/Algorithm/BalancedBrackets kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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