Valid Parentheses

来源:互联网 发布:襄阳网站搜索引擎优化 编辑:程序博客网 时间:2024/06/07 06:35

题目描述

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.

题目解答

解题思路

典型的栈问题,遇到’(‘, ‘{‘, ‘[’ 入栈, 遇到’}’, ‘)’, ‘]’出栈。

代码实现

public class Solution {    public boolean isValid(String s) {        if(s == null || s.length() == 0 || s.length()%2 == 1)            return false;        int strLen = s.length();        ArrayDeque<Character> stack = new ArrayDeque<>();        int i = 0;        while(i < strLen){            switch(s.charAt(i)){                case '(':                    stack.push('(');                    break;                case '{':                    stack.push('{');                    break;                case '[':                    stack.push('[');                    break;                case ')':                    //访问栈定元素                    if(stack.size() == 0 || stack.pop() != '(')                        return false;                    break;                case '}':                    if(stack.size() == 0 || stack.pop() != '{')                        return false;                    break;                case ']':                    if(stack.size() == 0 || stack.pop() != '[')                        return false;                    break;                default:            }            i++;        }        return stack.size() == 0;    }}
0 0
原创粉丝点击