Solution in JAVA


  • 0
    S
    public class Solution20 {
    
        public static boolean isValid(String s) {
        	Stack<Character> stack = new Stack<Character>();
            stack.push('0');
            if(s.length()%2!=0){
    			return false;
    		}
        	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)==')'){
        				if(stack.pop()=='('){
        					continue;
        				}else{
        					return false;
        				}
        			}
        			if(s.charAt(i)==']'){
        				if(stack.pop()=='['){
        					continue;
        				}else{
        					return false;
        				}
        			}
        			if(s.charAt(i)=='}'){
        				if(stack.pop()=='{'){
        					continue;
        				}else{
        					return false;
        				}
        			}
        		}
        	}
        	if(stack.peek()!='0'){
        		return false;
        	}
        	return true;
        }
    }
    
    

Log in to reply
 

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