Ruby简单栈的实现_Ruby_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > Ruby > Ruby简单栈的实现

Ruby简单栈的实现

 2013/7/10 4:36:42  nbkhic  程序员俱乐部  我要评论(0)
  • 摘要:共2个文件,第1个栈的实现Stack.rbclassStackdefinitialize@store=[]enddefpush(x)@store.pushxenddefpop@store.popenddefpeek@store.lastenddefempty?@store.empty?endendparen_match.rbrequire'Stack'defparen_match(str)stack=Stack.newlsym="{[(<"rsym="}])>"str
  • 标签:实现 Ruby

共2个文件,第1个栈的实现

Stack.rb

class="ruby" name="code">    class Stack
        def initialize
            @store = []
        end
        def push(x)
            @store.push x
        end
        def pop
            @store.pop
        end
        def peek
            @store.last
        end
        def empty?
            @store.empty?
        end
    end

paren_match.rb

    require 'Stack'
    def paren_match(str)
        stack = Stack.new
        lsym = "{[(<" rsym = "}])>"
        str.each_byte do |byte|
            sym = byte.chr
            if lsym.include? sym
                stack.push sym
            elsif rsym.include? sym
                top = stack.peek
                if lsym.index(top) != rsym.index(sym)
                    return false
                else
                    stack.pop
                end
            end
        end
        return stack.empty?
    end

    str1 = "(([(a+b))*(c-d)-(e*f))"
    str2 = "[[(a-(b-c))], [[x,y]]]"
    puts paren_match(str1)  #false
    puts paren_match(str2)  #true
发表评论
用户名: 匿名