共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