Skip to content

Instantly share code, notes, and snippets.

@t0rn
Last active August 3, 2018 17:27
Show Gist options
  • Save t0rn/a3e84547d9b898c16226a65e8285ccf9 to your computer and use it in GitHub Desktop.
Save t0rn/a3e84547d9b898c16226a65e8285ccf9 to your computer and use it in GitHub Desktop.
String extension for balancing by "open" and "close" substrings. String balanced algorithm using Swift
protocol StackProtocol {
associatedtype ElementType
var isEmpty: Bool { get }
mutating func pop() -> ElementType?
mutating func push(_ value: ElementType)
}
struct Stack<T>: StackProtocol {
fileprivate var array: [T] = []
//MARK: StackProtocol
typealias ElementType = T
var isEmpty: Bool {
return array.isEmpty
}
mutating func pop() -> T? {
return array.popLast()
}
mutating func push(_ value: T) {
array.append(value)
}
}
extension String {
func isBalanced(open:Set<Character>,close:Set<Character>) -> Bool {
var stack = Stack<Character>()
let xs = self.filter{open.contains($0) || close.contains($0)}
guard false == xs.isEmpty else {return false}
for char in xs {
if open.contains(char) {
stack.push(char)
}
else {
if stack.isEmpty {return false}
if let topChar = stack.pop(),
open.contains(topChar) && !close.contains(char) {
return false
}
}
}
return stack.isEmpty
}
}
//true
"((()))()".isBalanced(open: Set("("), close: Set(")"))
"[][[]][]".isBalanced(open: Set("["), close: Set("]"))
"([])[()]()[]".isBalanced(open: Set("(["), close: Set(")]"))
"()[]([])".isBalanced(open: Set("[("), close: Set("])"))
"()[]([])".isBalanced(open: Set("["), close: Set("]"))
"()[]([])".isBalanced(open: Set("("), close: Set(")"))
"⎨⎦⎣⎝⎛⎠«⎞<⟩»>⟨⎬".isBalanced(open: Set("⎨⎣⎝⎛«<⟨"), close: Set("⎬⎦⎠⎞»>⟩"))
//false
")(".isBalanced(open: Set("("), close: Set(")"))
"][".isBalanced(open: Set("["), close: Set("]"))
"()".isBalanced(open: Set("["), close: Set("]"))
"[]".isBalanced(open: Set("("), close: Set(")"))
//reverted
")(][".isBalanced(open: Set(")]"), close: Set("[("))
@t0rn
Copy link
Author

t0rn commented Aug 3, 2018

improved with Set for O(n) complexity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment