Braces in a string are considered to be balanced if they met the following conditions,
- All braces must be closed. braces come in a pair of the form of
(), {}, []
. The left brace opens the pair and the right one closes it. - In any set of nested braces, the braces between any pair must be closed.
For example, [{}]
is a valid grouping of braces but [}]{}
is not.
I tried with the below code snippet but not getting the expected result,
let firstBracketOpening = "("
let firstBracketClosing = ")"
let secondBracketOpening = "{"
let secondBracketClosing = "}"
let thirdBracketOpening = "["
let thirdBracketClosing = "]"
func check(for braces: String) -> Bool {
var isMissing = false
for char in brace {
isMissing = contains(char: char, in: brace)
if isMissing {
break
}
}
return isMissing ? false : true
}
func contains(char: Character, in string: String) -> Bool {
var isMissing = false
if firstBracketOpening.contains(char) {
isMissing = string.contains(firstBracketClosing) ? false : true
}
if secondBracketOpening.contains(char) {
isMissing = string.contains(secondBracketClosing) ? false : true
}
if thirdBracketOpening.contains(char) {
isMissing = string.contains(thirdBracketClosing) ? false : true
}
return isMissing
}
Any lead to the solution will be appreciated. Thanks in advance.
? false: true
= !isMissing, therefore it is redundant :P. Also @Bappaditya, what is "item" incheck(:String)
? – Reseebrace
– Coccidioidomycosis{[}]
? – Leucas