My java easy solution for Valid Parentheses


  • 0
    P
    public class Solution {
        public boolean isValid(String s) {
            Stack<Character> stack = new Stack<Character>();
            
            //s的长度是奇数直接返回false
            if (s.length() % 2 != 0) {
                return false;
            }
            else {//遇到左括号压栈,遇到右括号弹栈比较
                for(int i = 0; i < s.length(); i++) {
                    switch(s.charAt(i)) {
                        case '(':
                        case '[':
                        case '{':
                            stack.push(s.charAt(i));
                            break;
                        case ')':
                            if (stack.empty()){
                                return false;
                            }else {
                                if (! stack.pop().equals('(')) {
                                    return false;
                                }
                            }
                            break;
                        case ']':
                            if (stack.empty()){
                                return false;
                            }else {
                                if (! stack.pop().equals('[')) {
                                    return false;
                                }
                            }
                            break;
                        case '}':
                            if (stack.empty()){
                                return false;
                            }else {
                                if (! stack.pop().equals('{')) {
                                    return false;
                                }
                            }
                            break;
                    }
                }
                
                if (! stack.empty()) {
                    return false;
                }
            }
           
           return true; 
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.