Skip to content

Instantly share code, notes, and snippets.

@robertherdzik
Last active November 30, 2018 17:26
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 robertherdzik/3bd59a8d83862d6d796a418214b699b0 to your computer and use it in GitHub Desktop.
Save robertherdzik/3bd59a8d83862d6d796a418214b699b0 to your computer and use it in GitHub Desktop.
Find whether the given expression is balanced
import XCTest
let patterns: [String: String] = [
"{": "}",
"[": "]",
"(": ")"
]
func isValid(with input: String) -> Bool! {
let charArr = input.split(separator: " ")
var holder = [String]()
charArr.forEach { item in
let holderPrev = holder.last
if let holderPrev = holderPrev {
if patterns[holderPrev] ?? "" == item {
holder.popLast()
} else {
holder.append(String(item))
}
} else {
holder.append(String(item))
}
}
return holder.isEmpty
}
let input1 = "{ [ ( ) ] }"
XCTAssertTrue(isValid(with: input1)!)
let input2 = "{ [ } ]"
XCTAssertFalse(isValid(with: input2)!)
let input3 = "{ { [ ]"
XCTAssertFalse(isValid(with: input3)!)
let input4 = "{ [ ( ( ( ) ) ) ] } { }"
XCTAssertTrue(isValid(with: input4)!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment