Skip to content

Instantly share code, notes, and snippets.

@spurscho
Created January 6, 2020 02:59
Show Gist options
  • Save spurscho/1068000f154b5a6b97215e10a058602f to your computer and use it in GitHub Desktop.
Save spurscho/1068000f154b5a6b97215e10a058602f to your computer and use it in GitHub Desktop.
20. Valid Parentheses
class Solution {
func isValid(_ s: String) -> Bool {
var stack = [Character]()
let closingPairs: [Character:Character] = [ "{":"}", "[":"]", "(":")" ]
let openBrackets = Set<Character>(closingPairs.keys)
for char in s {
if openBrackets.contains(char) {
stack.append(char)
} else {
guard let last = stack.popLast() else {
return false
}
if closingPairs[last] != char {
return false
}
}
}
return stack.isEmpty
}
}
let sol = Solution()
let example = ""
print(sol.isValid(example))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment