20. Valid Parentheses

来源:互联网 发布:572-393的简便算法 编辑:程序博客网 时间:2024/06/05 10:23

问题描述:

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();    }}


原创粉丝点击