My 21 line Java solution(without ( ) [] {} in code)


  • 8
    W
    public class Solution {
    public boolean isValid(String s) {
        char [] arr = s.toCharArray();
    	Stack stack = new Stack();
    	for(char ch : arr){
    		if(stack.isEmpty()){
    			stack.push(ch);
    		}else{
    			char top = (char)stack.lastElement();
    			if(ch - top == 1 || ch - top == 2){
    				stack.pop();
    			}else{
    				stack.push(ch);
    			}
    		}
    	}
    	if(stack.isEmpty()){
    	    return true;
    	}
    	return false;
    }
    

    }


  • 0
    H

    Explanation on IF condition : Difference between ASCII values of any open and close bracket is either 1 or 2.


  • 0
    D

    wrong o/p for "[(){|]"


Log in to reply
 

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