Last active
August 3, 2018 17:27
-
-
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
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
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("[(")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
improved with Set for O(n) complexity