oj20. Valid Parentheses

来源:互联网 发布:java模拟器 编辑:程序博客网 时间:2024/04/27 04:42

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.

翻译:

给出只包含字符'('')''{''}''['']'的字符串定输入字符串是有效的。

括号必须以正确的顺序关闭,例如"()"或者"()[]{}"都是有效的,但"(]""([)]"没有。

思路:一开始以为括号必须两两出现,内部不能嵌套 ,提交后发现测试用例有嵌套形式,感觉题目交代的不是很清楚。判断嵌套字符立马想到栈,运行速度还比较快。

public boolean isValid(String s) {        char[] ca = s.toCharArray();        int len = ca.length;        if(len%2 != 0) return false;        Stack st = new Stack();        for(int i=0; i<len;i++){            if(ca[i]=='(' || ca[i]=='[' || ca[i]=='{')                 st.push(ca[i]);            else{                if(st.empty()) return false;                char temp = (char)st.pop();                if(ca[i]==')'&& temp== '(') continue;                if(ca[i]==']'&& temp== '[') continue;                if(ca[i]=='}'&& temp== '{') continue;                return false;            }        }        if(st.empty()) return true;        else return false;            }


0 0
原创粉丝点击