iOS Interview - Leetcode 20: Valid Parentheses

April 26, 20241 min read#swift, #interview, #leetcode

Leetcode: 20. Valid Parentheses

  • Primary idea: Use a stack to see whether the peek left brace is correspond to the current right one
  • Time Complexity: O(n)
  • Space Complexity: O(n)
func isValidParentheses(_ s: String) -> Bool {
    var stack = [Character]()

    for char in s {
        switch char {
        case "(", "[", "{":
            stack.append(char)
        case ")":
            if stack.popLast() != "(" {
                return false
            }
        case "]":
            if stack.popLast() != "[" {
                return false
            }
        case "}":
            if stack.popLast() != "{" {
                return false
            }
        default:
            continue
        }
    }

    return true
}

print(isValidParentheses("()")) // true
print(isValidParentheses("()[]{}")) // true
print(isValidParentheses("(]")) // false
Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024