何かやってみるブログ

興味をもったこと、趣味のこと、技術について色々書きます。

LeetCode Valid Parenthesesを解いてみた

問題

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

結果

f:id:s-takaya1027:20220309183713p:plain