Created
August 1, 2018 06:35
-
-
Save nhatlee/07f98b24b2a075dccd453ca6d5e94d45 to your computer and use it in GitHub Desktop.
ExpressionBalanced
This file contains 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 UIKit | |
let openBrackets: [Character] = ["(", "{", "["] | |
let closedBrackets: [Character] = [")", "}", "]"] | |
func ~=<T: Equatable>(pattern: [T], value: T) -> Bool { | |
return pattern.contains(value) | |
} | |
func isExpressionBalanced(_ expression: String) -> Bool { | |
guard !expression.isEmpty else{ return false } | |
var stack = [Character]() | |
for char in expression { | |
switch char { | |
case openBrackets: stack.append(char) | |
case closedBrackets: | |
guard !stack.isEmpty else { return false } | |
if(stack.last! == "(" && char == ")") || | |
(stack.last! == "{" && char == "}") || | |
(stack.last! == "[" && char == "]") { | |
stack.removeLast() | |
} | |
default: | |
break | |
} | |
} | |
return stack.isEmpty | |
} | |
isExpressionBalanced("{a}(b)c") | |
isExpressionBalanced("{a(b)c") | |
isExpressionBalanced("1234567890abc") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment