关闭

Valid Parentheses

标签: LeetCode
179人阅读 评论(0) 收藏 举报
分类:

题目描述

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:39787次
    • 积分:1840
    • 等级:
    • 排名:千里之外
    • 原创:148篇
    • 转载:1篇
    • 译文:0篇
    • 评论:1条
    博客专栏
    最新评论