leetcode -- Valid Parentheses

Valid Parenthesescode

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.leetcode

solution 1:get

class Solution {
    public boolean isValid(String s) {
       char[] chars = s.toCharArray();
        Map<Character, Character> pairs = new HashMap<Character,Character>();
        pairs.put('(', ')');
        pairs.put('[', ']');
        pairs.put('{', '}');

        Stack<Character> stack = new Stack<Character>();
        for(char c:chars){
            if(pairs.containsKey(c)){
                stack.push(pairs.get(c));
            }else {
                if (stack.isEmpty() || c != stack.pop())
                    return false;
            }
        }
        return stack.isEmpty();
    }
}

solution 2:input

public boolean isValid(String s){
        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 (s.charAt(i) == ')' && !stack.empty() && stack.peek() =='(')
                stack.pop();
            else if (s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[')
                stack.pop();
            else if (s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{')
                stack.pop();
            else
                return false;
        }
        return stack.empty();
    }
相關文章
相關標籤/搜索