LeetCode – 20. Valid Parentheses

題目連結: https://leetcode.com/problems/valid-parentheses/

// Time complexity: O(n) , n is the length of string
    func isValid(_ s: String) -> Bool {
        let pair: [Character: Character] = [")": "(",
                                            "}": "{",
                                            "]": "["]
        var stack: [Character] = []
        for c in s {
            if pair.values.contains(c) {
                stack.append(c)
            } else if pair[c] == stack.last {
                stack.removeLast()
            } else {
                return false
            }
        }
        return stack.isEmpty
    }

assert(isValid(""), "Error 1")
assert(!isValid("(("), "Error 2")
assert(!isValid("}}"), "Error 3")
assert(isValid("()"), "Error 4")
assert(!isValid("())"), "Error 5")

%d 位部落客按了讚: