class Solution {
fun isValid(s: String): Boolean {
val stack = mutableListOf<Char>()
for (i in 0 until s.length) {
when (s[i]) {
'(' -> stack.add('(')
'[' -> stack.add('[')
'{' -> stack.add('{')
')' -> {
if (stack.isEmpty()) return false
if (stack.last() != '(') return false
stack.removeAt(stack.size - 1)
}
']' ->{
if (stack.isEmpty()) return false
if (stack.last() != '[') return false
stack.removeAt(stack.size - 1)
}
'}' ->{
if (stack.isEmpty()) return false
if (stack.last() != '{') return false
stack.removeAt(stack.size - 1)
}
}
}
if (stack.isNotEmpty()) return false
return true
}
}
시간복잡도 : O(N)
공간복잡도 : O(N)
class Solution {
fun isValid(s: String): Boolean {
val stack = mutableListOf<Char>()
for (i in 0 until s.length) {
when (s[i]) {
'(' -> stack.add(')')
'[' -> stack.add(']')
'{' -> stack.add('}')
else -> {
if (stack.isEmpty() || stack.removeAt(stack.size - 1) != s[i]) {
return false
}
}
}
}
if (stack.isNotEmpty()) return false
return true
}
}
시간복잡도 : O(N)
공간복잡도 : O(N)