Solution for Valid parentheses in Java

  • 0

    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();
                return(true);  //obviously no mismatch
                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;
                if(ch=='(' || ch=='{' || ch=='['){
                    st.push(ch);  //if opening parenthesis then push it 
                                        //to the stack
                    ch2=st.pop();             //else pop and store 
                                                  //it to the ch2 variable
                    opening=getOpening(ch);  //get the corresponding opening 
                                                     //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);
        }//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.