DEV Community

Suchitra
Suchitra

Posted on • Edited on

3 2

JAVA STACK

In this problem we have to find whether the input string is valid sequence of parenhesis or not!
We just put our string like this:-
{}()
({()})
{}(
[]

And according to our input this program will give "true" if the sequence is valid otherwise "false".

   import java.util.*;
    class Solution{ 
    public static void 
    main(String []argh)
    {
Scanner sc = new Scanner(System.in);

while(sc.hasNext()) {
         String input=sc.next();
            //Complete the code

        }
      System.out.println(isValid(input));
          }
      }
        public static boolean 
    isValid(String s){
        if(s.charAt(0)==')'||s.charAt(0)=='}'||s.charAt(0)==']'){
            return false;
        }
       Stack<Character> stack=new Stack<>();
     for(int i=0;i<s.length();i++)
    {if(s.charAt(i)=='{'||s.charAt(i)=='('||s.charAt(i)=='[')
        { 
     stack.push(s.charAt(i));
        }
    else{
        if(stack.empty()){
            return false;
        }
    char open=findOpenBracket(s.charAt(i));
        char ch=stack.pop();
     if(ch!=open)   {
        return false;
         }
        }
    }
    if(stack.empty()){
        return true;
    }
    return false;
    }
    public static char findOpenBracket(char c)
    {
       if(c=='}')
          {
          return '{';
          }
       else if(c==')'){
           return '(';
          }
       else if(c==']'){
        return '[';
         }
        return ' ';
         }
        }
Enter fullscreen mode Exit fullscreen mode

If any doubt feel free to ask in comment:)
This problem is taken from the HackerRank !!
Happy Coding❤️

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay