Skip to content

Instantly share code, notes, and snippets.

@twhitt14
Last active April 16, 2019 05:05
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 twhitt14/484b5b627005946cb2472f4e78f29ac0 to your computer and use it in GitHub Desktop.
Save twhitt14/484b5b627005946cb2472f4e78f29ac0 to your computer and use it in GitHub Desktop.
// 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