問題
https://leetcode.com/problems/valid-parentheses/
解いた
# @param {String} s # @return {Boolean} def valid_operators ["()", "{}", "[]"] end def is_valid?(char) valid_operators.include? char end def close_operators [")", "}", "]"] end def close_operator?(char) close_operators.include? char end def is_valid(s) chars = s.chars stack = [] chars.each do |char| stack << char if close_operator?(char) && stack.length >= 2 test = stack[-2] + stack[-1] if is_valid?(test) stack = stack[0..-3] else break end end end p stack.empty? end
結果