Last active
April 16, 2019 05:05
-
-
Save twhitt14/484b5b627005946cb2472f4e78f29ac0 to your computer and use it in GitHub Desktop.
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
// Run in an Xcode Playground | |
let input = ")(()(" | |
let input2 = "))()))(" | |
let input3 = "))))((((" | |
let input4 = ")))()(()()((" | |
let input5 = "(()())" | |
let input6 = "" | |
let input7 = "()" | |
func solution(parentheses: String) -> String { | |
var solution = parentheses | |
// the strategy is to handle the outward facing leading & trailing parentheses first | |
// once those are calculated, just find the difference in the inner parentheses & add as many as are needed to even them out | |
let leadingLeftFacingParenthesesCount = parentheses.prefix { $0 == ")" }.count | |
let trailingRightFacingParenthesesCount = parentheses.reversed().prefix { $0 == "(" }.count | |
let stringWithLeadingLeftFacingParenthesesRemoved = parentheses.suffix(parentheses.count - leadingLeftFacingParenthesesCount) | |
let stringWithLeadingAndTrailingOpenParenthesesRemoved = stringWithLeadingLeftFacingParenthesesRemoved.prefix(stringWithLeadingLeftFacingParenthesesRemoved.count - trailingRightFacingParenthesesCount) | |
let innerRightFacingParenthesisCount = stringWithLeadingAndTrailingOpenParenthesesRemoved.replacingOccurrences(of: ")", with: "").count | |
let innerLeftFacingParenthesisCount = stringWithLeadingAndTrailingOpenParenthesesRemoved.replacingOccurrences(of: "(", with: "").count | |
let innerParenthesesDifference = innerLeftFacingParenthesisCount - innerRightFacingParenthesisCount | |
if leadingLeftFacingParenthesesCount > 0 { | |
(1...leadingLeftFacingParenthesesCount).forEach { _ in | |
solution = "(" + solution | |
} | |
} | |
if trailingRightFacingParenthesesCount > 0 { | |
(1...trailingRightFacingParenthesesCount).forEach { _ in | |
solution = solution + ")" | |
} | |
} | |
if innerParenthesesDifference < 0 { | |
(innerParenthesesDifference ... -1).forEach { _ in | |
solution = solution + ")" | |
} | |
} else if innerParenthesesDifference > 0 { | |
(1 ... innerParenthesesDifference).forEach { _ in | |
solution = "(" + solution | |
} | |
} | |
return solution | |
} | |
solution(parentheses: input) == "()(()())" | |
solution(parentheses: input2) == "(((())()))()" | |
solution(parentheses: input3) == "(((())))(((())))" | |
solution(parentheses: input4) == "((()))()(()()(()))" | |
solution(parentheses: input5) == "(()())" | |
solution(parentheses: input6) == "" | |
solution(parentheses: input7) == "()" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment