Swift solution always exceeds the time limit


  • 0

    Any idea what can I optimize?

    class Solution {
        func isValid(_ s: String) -> Bool {
            var stack: [String] = []
    
            for index in 0..<s.characters.count {
                let ch = char(from: s, at: index)
    
                switch ch {
                    case "[", "(", "{":
                        stack.append(ch)
    
                    case "]":
                        if let last = stack.last, last == "[" {
                            stack.removeLast()
                        } else {
                            return false
                        }
                    
                    case ")":
                        if let last = stack.last, last == "(" {
                            stack.removeLast()
                        } else {
                            return false
                        }
    
                    case "}":
                        if let last = stack.last, last == "{" {
                            stack.removeLast()
                        } else {
                            return false
                        }
                    default:
                        return false
                }
            }
            return stack.isEmpty
        }
        
        func char(from str: String, at index: Int) -> String {
            let stringIndex = str.index(str.startIndex, offsetBy: index)
            return String(str[stringIndex])
        }
    }
    

  • 0
    G

    @art_em_s

    class Solution {
        func isValid(_ s: String) -> Bool {
            var stack: [String] = []
            let array = Array(s.characters)
            
            for char in array {
                let str = String(char)
                print("1\(str)")
                switch str {
                case "[" :
                    stack.append("]")
                case "(":
                    stack.append(")")
                case "{":
                    stack.append("}")
                default:
                    if stack.isEmpty || (stack.popLast() != str) {
                        return false
                    }
                }
                
                
            }
            return stack.isEmpty
        }
    }```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.