The question says to write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it's invalid.
All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.
The tests should give these:
"(){}[]" => True
"([{}])" => True
"(}" => False
"[(])" => False
"[({})](]" => False
The code I've written is:
def validBraces(braces)
revBraces = braces.reverse
arr = []
i = -1
loop do
i += 1
if braces[i] == "(" && revBraces[i] == ")"
arr << 1
else
arr << 0
end
if braces[i] == ")" && revBraces[i] == "("
arr << 1
else
arr << 0
end
if braces[i] == "{" && revBraces[i] == "}"
arr << 1
else
arr << 0
end
if braces[i] == "}" && revBraces[i] == "{"
arr << 1
else
arr << 0
end
if braces[i] == "[" && revBraces[i] == "]"
arr << 1
else
arr << 0
end
if braces[i] == "]" && revBraces[i] == "["
arr << 1
else
arr << 0
end
break if i <= braces.length
end
if arr.include? 0
puts false
else
puts true
end
end
I cant tell where I've gone wrong and why it doesn't work.
The logics is wrong. You take braces and reverseBraces. And you don't think of cases where the braces are nested. But even when not nested the way you go through the string is not right. Better have a dictionary of "(", "{", "[", ")", "}", "]" and count their frequency (make the closing brackets' counts negative) and see whether they cancel themselves out by building a sum - it should be 0.