Valid Parentheses

原创 2015年11月19日 11:08:29

题目描述

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;
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Leetcode 32. Longest Valid Parentheses

问题描述 Given a string containing just the characters '(' and ')', find the length of the longe...

LeetCode OJ 20 Valid Parentheses [Easy]

LeetCode OJ 20 Valid Parentheses 题目描述: Given a string containing just thecharacters '(', ')', '{', ...

[leetcode]Longest Valid Parentheses

题目介绍: Given a string containing just the characters '(' and ')', find the length of the longe...

leetcode20:Valid Parentheses

Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and']',.....

Valid Parentheses

题目要求我们判断给定字符串s中所包含的三种括号形式是否合理。 合理的形式:() , ()[]{} ,{()}等。 不合理形式:({)} ,([)]等。解题思路: 用堆栈的方式,碰到左半边括号就入...

longest valid parentheses--LeetCode

Given a string containing just the characters '(' and ')', find the length of the longest valid (wel...

Valid Parentheses python题解

Valid Parentheses python题解

Leetcode: Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (we...

LeetCode 20. Valid Parentheses 辅助数据结构栈

Valid Parentheses 题意 注意 思路 代码 结果20. Valid Parentheses Given a string containing just the character...

Leetcode20: Valid Parentheses

这题的答题思路基本是对了,用字典来解决,不过,还是没有对stack的应用太熟悉,还需练习。 class Solution(object): def isValid(self, s):...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)