LeetCode(20):Valid Parentheses

本文介绍了一种使用栈数据结构来判断括号字符串是否有效的方法。通过遍历输入字符串,利用栈来跟踪并验证括号是否正确闭合。文章详细解释了实现思路及代码示例。

Valid Parentheses: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.

题意:给定一个字符串,由'(', ')', '{', '}', '['']'组成,判断这串字符串是不是有效的组合。

思路:使用栈来解决此题。遍历字符串,如果第一个字符为)} ]中的一个则直接返回false;否则将其压入栈中。接着处理下面的字符:

(1)如果是( { [中的一个则直接压入栈中

(2)如果是})]中的一个,则和栈顶元素比较:如果栈顶元素是遇到元素的匹配字符则栈顶元素出栈,否则返回false

最后判断栈是否为空,如果为空则返回true,否则返回false。

代码:

public boolean isValid(String s) {
        Stack  stack = new Stack ();
         if (s.length()<2) return false;
         String temp = String.valueOf(s.charAt(0));
         if (temp.equals(")")||temp.equals("}")||temp.equals("]")) return false;
         for(int i=0;i<s.length();i++)
         {
                temp = String.valueOf(s.charAt(i));
                if(temp.equals("(")||temp.equals("{")||temp.equals("[")){
                    stack.push(temp);
                }
                else if(!stack.isEmpty())
                {
                switch (temp) {
                    case ")":
                        if(("(").equals(stack.peek())){
                            stack.pop();
                            }else {
                                return false;
                            }
                        break;
                    case "}":
                        if(("{").equals(stack.peek())){
                            stack.pop();
                        }else {
                            return false;
                        }
                        break;
                    case "]":
                        if(("[").equals(stack.peek())){
                            stack.pop();
                        }else{
                            return false;
                        }
                        break;
                    default:
                        return false;
                    }
                }
                else {
                    return false;
                }
            } //for
         if (stack.isEmpty()){
             return true;
         }else {
            return false;
        }
    }

转载于:https://www.cnblogs.com/Lewisr/p/5115107.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值