DEV Community

Suchitra
Suchitra

Posted on • Updated on

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❤️

Top comments (0)