20. Valid Parentheses leetcode java

1.题目

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.

给定一个包含(){}[]的字符串,判断它是否是有效括号。

2.思路

用栈解决这个问题,用两个栈,s1和s2,s1里按序push进字符串s

①如果s2不为空,取s1和s2栈顶字符进行比较,如果满足isequal那么s2的栈顶pop掉

②如果s2为空,那么将s1栈顶push进s2

循环结束如果s2为空,那么这个字符有效,否则无效。

isequal函数的功能在于看传到这个函数的两个字符是否能配成一对,而且是有序的一对,比如“()“是一对,但是“)(”不是。

注意字符串相等不能用==,而是要用equals()函数。

3.程序

class Solution {
    public boolean isValid(String s) {
        Stack<String> s1=new Stack<String>();
        Stack<String> s2=new Stack<String>();
        String temp;
        for(int i=0;i<s.length();i++){
            s1.push(s.substring(i,i+1));
        }
        while(!s1.isEmpty()){
            temp=s1.pop();
            if(!s2.isEmpty()){
                if(isequal(temp,s2.peek())) {
                	s2.pop();
                }
                else {
                	s2.push(temp);
                }
            }
            else
            	s2.push(temp);
        }
        if(s2.isEmpty())
        	return true;
        return false;
    }	
    public boolean isequal(String a,String b) {
    	if((a.equals("{")&&b.equals("}"))||(a.equals("[")&&b.equals("]"))||(a.equals("(")&&b.equals(")")))
    		return true;
    	return false;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值