Last active
November 30, 2018 17:26
-
-
Save robertherdzik/3bd59a8d83862d6d796a418214b699b0 to your computer and use it in GitHub Desktop.
Find whether the given expression is balanced
This file contains hidden or 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 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