KtLeetcode/src/Test20.kt

44 lines
1.3 KiB
Kotlin
Raw Normal View History

2024-08-05 04:14:20 +02:00
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("]"))
}
}