美文网首页
20. Valid Parentheses

20. Valid Parentheses

作者: MoveOnLC | 来源:发表于2016-10-17 17:51 被阅读0次

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

    用一个stack解决问题,从头到尾扫描一下,遇到左括号压栈,遇到右括号就将stack的top元素和其配对弹出。如果中间遇到问题不能配对,或者到最后stack不空,就返回false。

    public class Solution {
        /**
         * @param s A string
         * @return whether the string is a valid parentheses
         */
        public boolean isValidParentheses(String s) {
            // Write your code here
            if (s.length() == 0) {
                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.isEmpty()) {
                        return false;
                    }
                     else if ((s.charAt(i) == ')' && stack.peek() == '(') 
                    || (s.charAt(i) == ']' && stack.peek() == '[')
                    || (s.charAt(i) == '}' && stack.peek() == '{')) {
                        stack.pop();
                    } else {
                        return false;
                    }
                }
            }
            
            return stack.isEmpty();
            
        }
    }
    

    相关文章

      网友评论

          本文标题:20. Valid Parentheses

          本文链接:https://www.haomeiwen.com/subject/dbhzyttx.html