Skip to content

Instantly share code, notes, and snippets.

@chnirt
Created May 21, 2022 08:54
Show Gist options
  • Save chnirt/8c56b596064677b3907016d9b9be15ad to your computer and use it in GitHub Desktop.
Save chnirt/8c56b596064677b3907016d9b9be15ad to your computer and use it in GitHub Desktop.
Balanced Brackets with multiple conditions
// There are strings that are made of brackets—[,], braces—{,}, and parentheses—(,). A string is regarded as a valid string of brackets when it meets the following conditions:
// In brackets, there can be brackets, braces, and parentheses.
// In braces, there can only be braces and parentheses.
// 2-1. "{[]()}" is invalid, because brackets are in braces.
// In parentheses, there can only be other parentheses.
// 3-1. "({()})" is invalid, because braces are in parentheses.
// All open brackets, braces, and parentheses must be closed by the corresponding number of brackets, braces, and parentheses.
// 4-1. "[{}(()]" is invalid. There are two(s, but only one corresponding ).
// All open brackets, braces, and parentheses must be closed in the correct order.
// 5-1. "[{()}}{]" is invalid, because { is closed in the wrong order.
// If a bracket, brace, or parenthesis is opened last, then it must close first.
// 6-1. "{(})" is invalid, because ) must come after }.
// Suppose a parameter pars is given, where pars is an array containing strings. Please write a function solution that returns an array where 1 indicates the validity and 0 the invalidity for each string in the given array.
// Constraints
// The length of pars—the number of strings—is between 1 and 10.
// The length of each element of pars is between 2 and 200,000.
// All strings are made up of the following six characters: '[', ']', '{', '}', '(', ')'
// Examples
// pars result
// ["{[]()}", "({()})", "[{}(()]", "[{()}}{]", "{(})"] [0, 0, 0, 0, 0]
// ["[(){{()}}]", "([])", "[()]()[{}]","(}", "{}", "[]", "()"] [1, 0, 1, 0, 1, 1, 1]
// Example #1
// Demonstrated in the prompt above. None of them are valid.
// Example #2
// "[(){{()}}]" meets the six conditions listed in the prompt above, and therefore is valid.
// With "([])", there are brackets in parentheses. It is therefore invalid.
// "[()]()[{}]" meets the six conditions listed in the prompt above, and therefore is valid.
// With "(}", the open parenthesis ( doesn't close with ). It is therefore invalid.
// "{}" meets the six conditions listed in the prompt above, and therefore is valid.
// "[]" meets the six conditions listed in the prompt above, and therefore is valid.
// "()" meets the six conditions listed in the prompt above, and therefore is valid.
// -----
import Foundation
enum Balance {
case balanced
case unbalanced(String)
}
extension String {
func isBalanced() -> Bool {
var stack = [Character]()
for char in self {
if ["[", "{", "("].contains(char) {
if let last = stack.last {
// print(last,char)
switch (last, char) {
case ("{", "["), ("(", "["), ("(", "{"):
return false
default:
// return .unbalanced("mismatched braces: \(top), \(char)")
break
}
}
stack.append(char)
} else if [")", "}", "]"].contains(char) {
if let top = stack.popLast() {
switch (top, char) {
case ("{", "}"), ("(", ")"), ("[", "]"):
break
default:
// return .unbalanced("mismatched braces: \(top), \(char)")
return false
}
} else {
// return .unbalanced("unexpected close brace: \(char)")
return false
}
}
}
if !stack.isEmpty {
// return .unbalanced("missing \(stack.count) closing braces")
return false
}
// return .balanced
// print(stack)
return true
// switch self.filter("()[]{}".contains)
// .replacingOccurrences(of: "{[]()}", with: "0")
// .replacingOccurrences(of: "({()})", with: "0")
// .replacingOccurrences(of: "([])", with: "0")
// .replacingOccurrences(of: "[(){{()}}]", with: "1")
// .replacingOccurrences(of: "[()]()[{}]", with: "1")
// .replacingOccurrences(of: "{}", with: "1")
// .replacingOccurrences(of: "[]", with: "1")
// .replacingOccurrences(of: "()", with: "1") {
// case "1": return 1
// case "0": return 0
// case self: return 0
// case let next: return next.isBalanced()
// }
}
}
func test(_ pars: [String]) -> [Int] {
pars.map{ (string) -> Int in
return String(string).isBalanced() ? 1 : 0
}
}
print(test(["{[]()}", "({()})", "[{}(()]", "[{()}}{]", "{(})"]))
// [0, 0, 0, 0, 0]
print(test(["[(){{()}}]", "([])", "[()]()[{}]","(}", "{}", "[]", "()"]))
// [1, 0, 1, 0, 1, 1, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment