Solution for Valid parentheses in Java


  • 0
    K

    This problem can be easily solved by using stack. We have to go through the string and every time we pick an opening parenthesis we push it to the stack and every time we hit a closing parenthesis we pop from the stack and compare it, if it is the matching pair of the closing parenthesis.
    At the end the stack should be empty .

     public boolean isValid(String s) {
            
            
            Stack<Character> st = new Stack<>();
           
            int len=s.length();
            
            if(len==0){
                return(true);  //obviously no mismatch
            }
            
            if(len%2==1){
                return(false);  //if it contains odd number of parenthesis
                                     //then it is false
            }                      
            
            int k=0;   //initialize a pointer
            char ch,ch2;  //for storing closing or opening parenthesis
            char opening;
            
            while(k<len){
                
                ch=s.charAt(k);
                
                if(ch=='(' || ch=='{' || ch=='['){
                    
                    st.push(ch);  //if opening parenthesis then push it 
                                        //to the stack
                    
                }else{
                    
                    ch2=st.pop();             //else pop and store 
                                                  //it to the ch2 variable
                    opening=getOpening(ch);  //get the corresponding opening 
                                                      //parenthesis 
                                                     //from the method 
                                                      //written bellow
                    if(ch2!=opening) return(false);  //if it does't match 
                                                     //then return false
                }
                
                k++;  //move to the next character of the string s
            }
            
            if(!st.isEmpty())   return(false);
            return(true);
            
           
            
        }//end isValid()
        
        private char getOpening(char ch){
            
            if(ch==')') return '(';
            if(ch=='}') return '{';
            if(ch==']') return '[';
            
            return('E');     //this line is never executed 
                               //so you can send any character you like
            
        }//end of getOpening() method
    
    

Log in to reply
 

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