leetcode-program

Question 20: Valid Parentheses

Link

Solution

#SOLUTION-EXPLANATION The symbols mentioned in the question are mainly three -. ‘()’,’{}’,’[]’.

Here we use a stack to push these symbols into it.

With the help of a loop we push these symbols onto it.

After doing so we use ‘peek()’ method of stack to find out the top most element of stack.

For instance if we encounter a ‘)’ we check to see if top most element is a ‘(‘ using ‘peek()’ method, if found we pop it.

In the end if stack is empty the string is valid else its not.

Code

Java

class Solution {
    public boolean isValid(String s) {
        char st[] = s.toCharArray();


        if(st[0] == ')' || st[0] == '}' || st[0] == ']')
        return false;

        Stack<Character> s1 = new Stack<>();

        for(int i=0;i<st.length;i++){
            if(st[i]=='(' || st[i] == '{' || st[i] == '[') {
                s1.push(st[i]);
            }
            else if(st[i] == ')' || st[i] == '}' || st[i] == ']'){
                if(s1.empty())
                    return false;
                if(st[i]==')' && s1.peek()=='(')
                    s1.pop();
               else if(st[i]=='}' && s1.peek()=='{')
                    s1.pop();
                else if(st[i]==']' && s1.peek()=='[')
                    s1.pop();
                else
                    return false;
            }
        }

        if(s1.empty())
            return true;
        else
            return false;
    }
}