leetcode [Valid Parentheses]

    public class Solution {  
        public boolean isValid(String s) {  
            boolean res = true;  
            Stack<Character> stack = new Stack<Character>();  
            Character ch, chPop;  
            for(int i = 0; i < s.length(); i++){  
                ch = s.charAt(i);  
                if(ch == '{' || ch == '[' || ch == '('){  
                    stack.push(ch);  
                }  
                if(ch == '}' || ch == ']' || ch == ')'){  
                    if(stack.isEmpty()){  
                        res = false;  
                        break;  
                    }  
                    else{  
                        chPop = stack.pop();  
                        if(!((ch == '}' && chPop =='{')   
                           || (ch == ']' && chPop =='[')   
                           || (ch == ')' && chPop =='('))){  
                            res = false;  
                            break;  
                        }  
                    }  
                }  
            }  
            if(!stack.isEmpty()){  
                res = false;  
            }  
            return res;  
        }  
    }  

 代码整洁:

    class Solution{  
        public boolean isValid(String s) {  
            boolean res = true;  
            Stack<Character> stack = new Stack<Character>();  
            Character ch, chPop;  
            for(int i = 0; i < s.length(); i++){  
                ch = s.charAt(i);  
                if(ch == '{' || ch == '[' || ch == '('){  
                    stack.push(ch);  
                }  
                if(ch == '}' || ch == ']' || ch == ')'){  
                    if(stack.isEmpty()) { res = false; break; }//要弹栈首先要满足栈非空  
                    else{  
                        chPop = stack.pop();  
                        if(!((ch == '}' && chPop =='{') || (ch == ']' && chPop =='[')  || (ch == ')' && chPop =='('))){  
                            res = false;  
                            break;  
                        }  
                    }  
                }  
            }  
            if(!stack.isEmpty()){ res = false; }  
            return res;  
        }  
    }  

 

posted @ 2017-12-03 14:03  melon1ce  阅读(47)  评论(0)    收藏  举报