Swift solution


  • 0
    U
    func isValid(_ s: String) -> Bool {
            
             var stack : Array = Array<Character>()
    
            
            let dic = ["]":"[", "}":"{", ")":"("]
            
            for character in s.characters
            {
                switch character {
                    
                case "(", "[", "{":
                    stack.append(character)
                break
               
                case ")", "]", "}":
                    
            if let lastCharacter = stack.last{
                        
                if (String(lastCharacter) != dic[String(character)])
                {
                    return false
                }
                
                stack.popLast()
            }else
            {
                return false
            }
                    
                    
                break
                
                default:
                    break
                }
            }
            return stack.isEmpty
        }
    

Log in to reply
 

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