Skip to content

Instantly share code, notes, and snippets.

@nhatlee
Created August 1, 2018 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhatlee/07f98b24b2a075dccd453ca6d5e94d45 to your computer and use it in GitHub Desktop.
Save nhatlee/07f98b24b2a075dccd453ca6d5e94d45 to your computer and use it in GitHub Desktop.
ExpressionBalanced
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