【LeetCode】Valid Parentheses 解题报告

来源:互联网 发布:小白网络技术论坛 编辑:程序博客网 时间:2024/06/03 12:29

【LeetCode】Valid Parentheses 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/valid-parentheses/#/description

题目描述:

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.

Ways

第一感觉就是栈,但是怎么用呢。这个方法就是如果左边的括号出现,那么把右边的括号放到栈里,这样,如果不是左边的括号出现时,弹出右边的括号,判断栈里边最后入的那个元素和目前的右边括号是否相同。如果不同就返回false。有种可能是入栈很多左括号,右括号个数小于左括号个数,所以最后也要判断一下栈是否为空,如果是空说明左右括号个数正好匹配。

public class Solution {    public boolean isValid(String s) {        if(s == null || (s.length() & 1) == 1){            return false;        }        Stack<Character> stack = new Stack<Character>();        for(char c : s.toCharArray()){            if(c == '('){                stack.push(')');            }else if(c == '['){                stack.push(']');            }else if(c == '{'){                stack.push('}');            }else if(stack.isEmpty() || stack.pop() != c){                return false;            }        }        return stack.isEmpty();    }}

Date

2017 年 5 月 17 日

原创粉丝点击