20. 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.


第一次遇到字符匹配的问题,完全不知从何入手啊~想了半天没思路然后参考了一般别人的答案突然灵光一现:类似“{({})}”,“{()}”都是轴对称图形啊!那就用堆栈存序列:当遇到“(”存“)”、遇到{存}遇到【存】,最后判断生成的堆栈里面的字符串和原来的是否相同就行了呀!然而。。。。图森破!!eg: “{}【】()”这也不是轴对称啊。。。跪了,但是,我的方法可以用来验证是否轴对称哇~~嘻嘻,记录在这里~

public static boolean isValid(String s) {//判断是否轴对称
        Stack<Character> res = new Stack<Character>();
        String gene = "";
        for(char c:s.toCharArray()){
            if(c=='(')
                res.push(')');
            if(c==')')
                res.push('(');
            if(c=='{')
                res.push('}');
            if(c=='}')
                res.push('{');
            if(c=='[')
                res.push(']');
            if(c==']')
                res.push('[');
        }
        boolean flag = true;
        while(flag){
        	char thispop = res.pop();
            gene = gene + String.valueOf(thispop);
            if(res.isEmpty())
            	flag = false;
        }
        if(gene.equals(s))
        	return true;
        return false;
    }
	

然后跪了之后,继续看答案的我。。。。明白了别人的真实意图:只有遇到“(”、“{”、“【”的时候才压栈其对应另一半,然后遇到“}”、“】”、“)”的时候就弹栈。也就是说,堆栈里面存的是还没找到另一半的符号的 应该有的另一半啊(看看人家多机智,都知道自己喜欢啥样的哈哈哈) 由于堆栈先进后出的特点就可以保证符号的顺序性了~~机智!!

class Solution {
    public static boolean isValid(String s) {
        Stack<Character> res = new Stack<Character>();
        
        for(char c:s.toCharArray()){
            if(c=='(')
                res.push(')');
            
            else if(c=='{')
                res.push('}');
            
            else if(c=='[')
                res.push(']');
            else if(res.isEmpty()||res.pop()!=c)
                return false;
        }
        return res.isEmpty();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值