LeetCode编程练习

来源:互联网 发布:学历网络教育费用 编辑:程序博客网 时间:2024/06/08 07:57

题目:

      Given a string containing just the characters'(',')','{', '}', '[' and']', determine if the input string is valid.

      The brackets must close in the correct order,"()" and"()[]{}" are all valid but"(]" and"([)]" are not.

      给定一个字符串,只包含字符'(','),' {','} ','['和'],判断输入字符串是否有效。括号必须以正确的顺序关闭”和“()(){ }”都是有效的但“()”和“()”。


思路:

  这是一道验证配对情况的题,是对栈的应用,有效括号就是有一个右括号必定就有一个左括号在前面,将左括号push进栈中,遇到右括号时再pop消除,这种时候不必担心连续不同种类左括号,有效的括号对最终还是会有紧邻的括号对,比如说{[]}。栈在peek或者pop操作之前要验证非空,否则会抛出StackEmptyException。






原创粉丝点击