Created
January 6, 2020 02:59
-
-
Save spurscho/1068000f154b5a6b97215e10a058602f to your computer and use it in GitHub Desktop.
20. Valid Parentheses
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
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