Valid parentheses

来源:互联网 发布:itunes管理iphone软件 编辑:程序博客网 时间:2024/05/04 08:55

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.

分析:

用stack解决,一个一个检查character,如果是左括号就放入stack;如果是右括号,看stack是否为空,若为空则不匹配,若不为空,判断pop出的是否匹配。全部检查完后,看stack是否为空,若空则valid,若不空证明还有没有匹配的所以不valid。

code:


publicclass Solution {

    public boolean isValid(String s) {

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

            } else {

                if (stack.size() == 0) {

                    returnfalse;

                }

                char top = stack.pop();

                if (s.charAt(i) ==')') {

                    if (top !='(') {

                        returnfalse;

                    }

                } else if (s.charAt(i) == '}') {

                    if (top !='{') {

                        returnfalse;

                    }

                } else if (s.charAt(i) == ']'){

                    if (top !='[') {

                        returnfalse;

                    }

                }

            }

        }

        return stack.size() == 0;

    }

}


0 0
原创粉丝点击