How to check validity of closed brackets, parentheses or brackets in Ruby
regex, rubular, ruby
Solution
I think it might be complicated to use `regex` to solve this problem. Here is a potential solution: You may use a stack to record the left symbol like `{`, `[`, `(` in the traverse. Each time you met the right symbol, just check whether the symbol on the stack top matches this right symbol. Simply return `false` if not match.
Below is my code:
def valid_string?(str)
stack = []
symbols = { '{' => '}', '[' => ']', '(' => ')' }
str.each_char do |c|
stack << c if symbols.key?(c)
return false if symbols.key(c) && symbols.key(c) != stack.pop
end
stack.empty?
end
puts valid_string?('[ ]') # returns true
puts valid_string?('[ ') # returns false
puts valid_string?('[ ( text ) {} ]') # returns true
puts valid_string?('[ ( text { ) } ]') # returns false
Problem
Write a method 'valid_string?' that accepts a string. It returns true if the brackets, parentheses, and curly braces close correctly. It returns false otherwise. ``` valid_string?("[ ]") # returns true valid_string?("[ ") # returns false valid_string?("[ ( text ) {} ]") # returns true valid_string?("[ ( text { ) } ]") # returns false ``` My code: Is returning false for everything. Even tried using explicit booleans for individual cases {} || () ||, etc. Did not work. Either returns true or false for everything. Is it my driver code? ``` def valid_string?(str) if str == ("\[\s+]") true else false end end ``` UPDATED SOLUTION:------------------------------------------------ Yes! #match definitely worked out better! Although my last line of test code is evaluating to true. When it should be false. . . ``` def valid_string?(str) if str.match "(\\[.+\\])" || "|(\\(\\))" || "|({})" return true else return false end end puts valid_string?("[ ]") # returns true puts valid_string?("[ ") # returns false puts valid_string?("[ ( text ) {} ]") # returns true puts valid_string?("[ ( text { ) } ]") # returns false ```