Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Last active September 16, 2019 00:00
Show Gist options
  • Select an option

  • Save jakehawken/07a7835e2cc12b8613c0021fc557100f to your computer and use it in GitHub Desktop.

Select an option

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.
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