Simple Swift solution using a stack


  • 0
    2

    Here is a solution in swift using a stack to push opening parentheses. If the top of the stack does not contain opening parentheses that matches the next incoming parentheses, we know the string is not valid. If the string total length is odd or less than 2 we also know the parentheses won't be valid. We pop the top of the stack the opening and closing parenthesis match and check at the end if the stack is empty, if so, we have a winner.

    
        var arr = [Character]()
        for (i,c) in string.characters.enumerated() {
            if (String(c) == "(" || String(c) == "[" || String(c) == "{") {
                arr.append(c)
            } else {
                guard let p = arr.last  else {
                    return false
                }
                if ((String(c) == ")" && String(p) != "(") || (String(c) == "]" && String(p) != "[") || (String(c) == "}" && String(p) != "{")) {
                    return false
                }
                arr.popLast()
            }
        }
        return arr.count == 0
    

Log in to reply
 

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