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.


此题在数据结构与算法经典问题解析(Java语言描述)P78 中有详细描述:

Stack的用法如下:

知识点
1.Character 类型的对象包含类型为 char 的单个字段
2.stack.size()是调用其父类Vector中的方法

最后,程序的代码为:

/** * author:YangzYuan * function:Valid Parentheses */
class Solution {
    public boolean isValid(String s) {
        /**长度为0或者1,肯定构不成一对符号 */
        if(s.length()==0 || s.length()==1) {
            return false;
        }

        Stack<Character> stack=new Stack<Character>();
        for(int i=0;i<s.length();i++) {
            if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='[') {
                stack.push(s.charAt(i));//此处是算法 b)-->2)
            }
            else {
                if(stack.size()==0) {
                    return false;
                }
                /**接下来就判断离左开口 ),},] * 是否是其对应的右开口符号了 * 且右开口符号判断完一次就不要了 * 这就是放到栈里面的原因 */
                char top=stack.pop();
                if(s.charAt(i)==')') {
                    if(top!='(') {
                        return false;
                    }
                }
                if(s.charAt(i)==']') {
                    if(top!='[') {
                        return false;
                    }
                }
                if(s.charAt(i)=='}') {
                    if(top!='{') {
                        return false;
                    }
                }
            }
        }
        return stack.size()==0;//最后判断是否所有的左开口是否都匹配完成

    }
}