[leetcode] ValidParentheses

package leetcode;

import java.util.Stack;

/**
* <pre>
* 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.
* </pre>
*/
public class ValidParentheses {

    public class Solution2 {
        public boolean isValid(String s) {
            Stack<Integer> stack = new Stack<Integer>();
            stack.push(0);
            for (int i = 0; i < s.length(); i++) {
                int c = s.charAt(i);
                if (stack.peek() + 1 == c || stack.peek() + 2 == c)
                    stack.pop();
                else
                    stack.push(c);
            }
            return stack.size() == 1;
        }
    }

    public class Solution {

        public boolean isValid(String s) {
            Stack<Integer> stack = new Stack<Integer>();
            for (int i = 0; i < s.length(); i++) {
                int c = s.charAt(i);
                if (stack.isEmpty()) {
                    stack.push(c);
                    continue;
                }
                int tem = stack.peek();
                if (tem + 1 == c || tem + 2 == c)
                    stack.pop();
                else
                    stack.push(c);
            }
            return stack.isEmpty();
        }
    }

}

你可能感兴趣的:(LeetCode)