Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Thursday, August 3, 2017

Longest valid Parentheses


Problem :
We need to find longest valid () in string

Ex:

()(()  2

()(((()()) 6 


Code:
Every time check with previous longest ( ) and current.
Initialize stack with -1 so that when we pop index of '(' , we will be having index-1 so that if we subtract it , it always comes in %2.

import java.util.*;
import java.lang.*;
import java.io.*;
class Hackerranksolutionc
 {
     public static int check(String str)
     {
         int res=0;
         Stack<Integer> st=new Stack<Integer>();
         st.push(-1);
         for(int i=0;i<str.length();i++)
         {
             if(str.charAt(i)=='(')
             {
                 st.push(i);
             }
             else if(str.charAt(i)==')')
             {
                 st.pop();
                 if(!st.empty())
                 res=Math.max(res,i-st.peek());
                 else
                 st.push(i);
             }
         }
         return res;
     }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
   String str=new String(ab.next());
   System.out.println(check(str));
}
}

}

0 Comments:

Post a Comment

Stats