def balanced?(a)
h = {'{' => '}', '(' => ')', '}' => '', ')' => ''}
return false unless h[a.shift] == a.pop until a.empty?
true
end
看了之前的回复才发现没有考虑 {()()} 的情况,
def balanced?(a)
h = {'{' => '}', '(' => ')'}
b = []
until a.empty?
e = a.shift
e == h[b.last] ? b.pop : b << e
end
b.empty?
end