RSS Amplifier

Swift by An Tran · Apr 26, 2024

iOS Interview - Leetcode 20: Valid Parentheses

0
Sign in to vote or save

This page did not load. You can still read it on the original site — the toolbar below keeps your place in the directory.

Leetcode: 20. Valid Parentheses Primary idea: Use a stack to see whether the peek left brace is correspond to the current right one Time…

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

Read on antran.app

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.