KtLeetcode/src/Test20.kt
2024-08-05 10:14:20 +08:00

44 lines
No EOL
1.3 KiB
Kotlin

class Test20 {
class Solution {
fun isValid(s: String): Boolean {
val stack = ArrayDeque(listOf<Char>())
for (c in s) {
when(c){
')' ->{
if (stack.isEmpty() || stack.last() != '('){
return false
}else{
stack.removeLast()
}
}
'}' ->{
if (stack.isEmpty() || stack.last() != '{'){
return false
}else{
stack.removeLast()
}
}
']' ->{
if (stack.isEmpty() || stack.last() != '['){
return false
}else{
stack.removeLast()
}
}
else -> {
stack.addLast(c)
}
}
}
return stack.isEmpty()
}
}
fun test(): Unit {
println(Solution().isValid("()"))
println(Solution().isValid("()[]{}"))
println(Solution().isValid("(]"))
println(Solution().isValid("]"))
}
}