【Ruby】【アルゴリズム】スタックを使った「括弧の対応を調べるプログラム」
Rubyは、クラスを再オープンできるところが面白いです。
でも眠いよ。
問題
3種類の括弧 (), {}, [] を含む文字列において,括弧の対応に整合性がとれているかどうかを判断する
解答
class Staple attr_accessor :column, :type def initialize( column, type ) @column = column @type = type end end class String def what_head_staple case self when ')' str = '(' when '}' str = '{' when ']' str = '[' end return str end def staple_check stack = [] self.scan(/./).each_with_index do |char, i| if char.is_head_staple? staple = Staple.new(i , char) stack.push(staple) next end if char.is_end_staple? if stack.empty? return "column: " + i.to_s + " - the tag is not good" elsif char.what_head_staple != stack.last.type return "column: " + i.to_s + " - the tag is not good" elsif stack.pop end end end if stack.empty? return "ok" else return "column: " + stack.first.column.to_s + " - the tag is not good" end end def is_head_staple? return true if self == '(' || self == '{' || self == '[' end def is_end_staple? return true if self == ')' || self == '}' || self == ']' end end p "x(abc)".staple_check p "x(abc}".staple_check p "]x(abc)".staple_check p "x(abc)}".staple_check p "((abc)".staple_check
■実行結果
"ok" "column: 5 - the tag is not good" "column: 0 - the tag is not good" "column: 6 - the tag is not good" "column: 0 - the tag is not good"