Valid Parentheses Program in Java

in this article we are going to Write the program of checking valid Parentheses in java

Valid Parentheses Solution

validParentheses.java

package gangforcode;

import java.util.Stack;

public class validParentheses {
    public static Boolean validParentheseCheck(String x)
    {


        if(x.length()<=1){
            return false;
        }

        Stack<Character> stk= new Stack<>();
        for(int i=0;i<x.length();i++){
            if(x.charAt(i)=='[' || x.charAt(i)=='{' || x.charAt(i)=='('){

                stk.push(x.charAt(i));

            }
            if(stk.isEmpty())
                return false;

            if(!stk.isEmpty())
            {

                if(x.charAt(i)==']'){

                    if(stk.peek()=='['){
                        stk.pop();
                    }

                    else{
                        return false;
                    }
                }
                else if(x.charAt(i)=='}'){

                    if(stk.peek()=='{'){
                        stk.pop();
                    }

                    else{
                        return false;
                    }
                }
                else if(x.charAt(i)==')'){

                    if(stk.peek()=='('){
                        stk.pop();
                    }

                    else{
                        return false;
                    }
                }
            }

        }
        if(stk.isEmpty())
        {
            return true;
        }
        else{
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println(validParentheseCheck("{{}[([])]}["));
    }

}

Output :-

valid parentheses

The output for valid parentheses is false, because the given parentheses string is not a valid parenthese.

Similar Java tutorial

data types in java – https://gangforcode.com/data-types-in-java/
identifiers in java – https://gangforcode.com/identifiers-in-java/
keywords in java – https://gangforcode.com/keywords-in-java/

Leave a Comment