leetcode20--valid parentheses


class Solution {
    public boolean isValid(String s) {
         if (s == null || s.length() % 2 != 0) {
            return false;
        }
        Stack stack = new Stack<>();
        char c[] = s.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i]!='{'&&c[i]!='}'&&c[i]!='('&&c[i]!=')'&&c[i]!='['&&c[i]!=']'){
                return false;
            }
            if (!stack.empty()){
                char character = stack.peek();
                if(IsMatch(character,c[i])){
                    stack.pop();
                }else{
                    stack.push(c[i]);
                }
            }else
            {
                stack.push(c[i]);
            }
        }
        return stack.empty();
    }
 
    private boolean IsMatch(char character, char c) {
        if ((character =='{'&&c=='}')||(character=='['&&c==']')||(character=='('&&c==')')) {
            return true;
        }
        return false;
    }
    
}

你可能感兴趣的:(leetcode)