My concise solution in JAVA using a stack


  • 0
    B
    public class Solution {
     Stack<Character> st = new Stack<Character>();
    int[] par = new int[128];
    public boolean isValid(String s) {
        par['('] = 1;
        par['['] = 1;
        par['{'] = 1;
        par[')'] = 2;
        par[']'] = 2;
        par['}'] = 2;
        
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if(par[c] == 1) st.push(c);
            if(par[c] == 2){
                if( st.isEmpty() || c - st.pop() > 2)return false;
            }
            
        }
        if(st.isEmpty())return true;
        else return false;
    }
    

    }


Log in to reply
 

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