哪位好人帮我解道书上的题目
有一个数组存放了(、)、{、}4种元素。请定义一个balanced?方法,检查这个数组的括号是否对称。所谓的“括号是否对称”是指:
1、{的数量与}相同
2、(的数量与)相同
3、“()”的对应关系与“{}”的对应关系没有交叉
p balanced?(["(","{","{","}","(",")","}","(",")",")"])
#=> true
p balanced?(["(","{","{","}","(","}",")",")"])
#=> false
所谓的“交叉”是指["(","{",")","}"]这样括号只有其中一边被括在另一对括号里的情况。而["(","{","}",")"]这样一级对应的括号被括在另一对括号里,就不算是“交叉”。
现在初学ruby,这个问题不知道咋搞,求指点,谢谢
[解决办法]
- -学过数据结构么,弄个栈就行了,后入先出