[LeetCode]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.

判断已给的只包含 '(' ')' '{' '}' '['  and  ']' 的字符串是否合法.

解题思路

    看到此类题立马应该想到使用栈。遇到右括号则应检查是否和栈顶元素匹配,遇到左括号应该入栈。
    在解题过程中,使用了一点小技巧来避免过的来判定括号类型。我们定义:
    Value(() = 0 ,Value()) = 5;
    Value({) = 1,Value(}) = 4;
    Value([) = 2,Value(]) = 3;
    那么相匹配的两个括号的Value值的和必定为5.

   另外:需要考虑到栈为空遇到右括号的情况。

代码

 public boolean isValid(String s) {
         if(s==null)
        	return true;
        if(s.length()==0)
        	return true;
        
        Stack<String> stack = new Stack<String>();
        String ch = "";
        int value;
        for(int i = 0;i < s.length();i++){
        	ch = s.charAt(i)+"";
        	value = getBracketsValue(ch);
        	if(value >=3){
        		if(stack.size()==0){
        			return false;
        		} else {
        			if(getBracketsValue(stack.peek())+value==5){
        				stack.pop();
        			} else {
        				return false;
        			}
        		}
        	} else {
        		stack.push(ch);
        	}
        }
        
        if(stack.isEmpty()){
        	return true;
        }
        return false;
    }
    
    public  int getBracketsValue(String s){
		if(s.equals("(")){
			return 0;
		} else if(s.equals(")")){
			return 5;
		} else if(s.equals("{")){
			return 1;
		} else if(s.equals("}")){
			return 4;
		}else if(s.equals("[")){
			return 2;
		} else if(s.equals("]")){
			return 3;
		} else {
			return -1;
		}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值