Last active
September 16, 2019 00:00
-
-
Save jakehawken/07a7835e2cc12b8613c0021fc557100f to your computer and use it in GitHub Desktop.
Leetcode #20: Takes in a string of braces (any mix of parentheses, square brackets, and curly braces) and returns whether they are validly delimited.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| enum ParenthesisType: CaseIterable { | |
| case round | |
| case square | |
| case curly | |
| var open: Character { | |
| switch self { | |
| case .round: | |
| return "(" | |
| case .square: | |
| return "[" | |
| case .curly: | |
| return "{" | |
| } | |
| } | |
| var close: Character { | |
| switch self { | |
| case .round: | |
| return ")" | |
| case .square: | |
| return "]" | |
| case .curly: | |
| return "}" | |
| } | |
| } | |
| static func from(character: Character) -> ParenthesisType? { | |
| for type in ParenthesisType.allCases { | |
| if type.open == character || type.close == character { | |
| return type | |
| } | |
| } | |
| return nil | |
| } | |
| } | |
| private var stack = [ParenthesisType]() | |
| func isValid(_ s: String) -> Bool { | |
| for character in s { | |
| guard let type = ParenthesisType.from(character: character) else { | |
| return false | |
| } | |
| if character == type.open { | |
| stack.append(type) | |
| } | |
| else if stack.last == type { | |
| stack.removeLast() | |
| } | |
| else { | |
| return false | |
| } | |
| } | |
| return stack.isEmpty | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment