- class Solution {
- fun isValid(s: String): Boolean {
- var stack : MutableList<Char> = mutableListOf()
- for (char in s){
- if(char == '}' || char == ')' || char == ']'){
- val popedStack = if(stack.size > 0){
- stack.removeAt(stack.size-1)
- }else{
- 'x'
- }
- when(char){
- '}' -> if(popedStack != '{') return false
- ')' -> if(popedStack != '(') return false
- ']' -> if(popedStack != '[') return false
- }
- }else{
- stack.add(char)
- }
- }
- return stack.size == 0
- }
- }
注意 : "[(])"的輸出結果是false。但"[()]"為true。
(用時45分鐘)
0 comments:
張貼留言