Ruby实现栈及表达式中不配对括号检查
共2个文件,第1个栈的实现
Stack.rb
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? endend
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) #falseputs paren_match(str2) #true