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.
这道题虽然很简单,但是坑很多
public class Solution {
    public boolean isValid(String s) {
        Stack q = new Stack();
        for(int i = 0; i<s.length();i++){
            if(s.charAt(i) == '('){
                q.add(")");
            }
            if(s.charAt(i) == '{'){
                q.add("}");
            }
            if(s.charAt(i) == '['){
                q.add("]");
            }
            if(s.charAt(i) == ')'){
                if(!(!q.isEmpty() &&q.pop().toString() == ")")) return false;
            }
            if(s.charAt(i) == '}'){
                if(!(!q.isEmpty() &&q.pop().toString() == "}")) return false;
            }
            if(s.charAt(i) == ']'){
                if(!(!q.isEmpty() && q.pop().toString() == "]")) return false;
            }
            
        }
        if(q.isEmpty()){
            return true;
        }
        else{
           return false; 
        }
        
    }
}
			    	微信扫一扫
			    
			    	支付宝扫一扫