Skip to main content

Longest valid Parentheses-[HARD/IMP/STACK]-100th post!!

100th post
Company:Google
Given a string consisting of opening and closing parenthesis, find length of the longest valid parenthesis substring.
Examples:
Input : ((()
Output : 2
Explanation : ()
Input: )()())
Output : 4
Explanation: ()()
Input:  ()(()))))
Output: 6
Explanation:  ()(())
Input:
First line contains the test cases T.  1<=T<=500
Each test case have one line string S of character'(' and ')' of length  N.  1<=N<=10000
Example:
Input:
2
((()
)()())
Output:
2
4
CODE:
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
int m= sc.nextInt();
for(int mi=0;mi<m;mi++){
   String s= sc.next();
   System.out.println(findMaxLen(s));
}
}
public static int findMaxLen(String str)
    {
        int n = str.length();
       Stack<Integer> stk = new Stack<>();
        stk.push(-1);
      
        // Initialize result
        int result = 0;
      
        // Traverse all characters of given string
        for (int i=0; i<n; i++)
        {
            // If opening bracket, push index of it
            if (str.charAt(i) == '(')
              stk.push(i);
      
            else // If closing bracket, i.e.,str[i] = ')'
            {
                // Pop the previous opening bracket's index
                stk.pop();
      
                // Check if this length formed with base of
                // current valid substring is more than max 
                // so far
                if (!stk.empty())
                    result = Math.max(result, i - stk.peek());
      
                // If stack is empty. push current index as 
                // base for next valid substring (if any)
                else stk.push(i);
            }
        }
      
        return result;
    }
}
EXECUTION TIME: 0.3s
Algorithm:
1) Create an empty stack and push -1 to it. The first element
   of stack is used to provide base for next valid string. 

2) Initialize result as 0.

3) If the character is '(' i.e. str[i] == '('), push index 
   'i' to the stack. 
   
2) Else (if the character is ')')
   a) Pop an item from stack (Most of the time an opening bracket)
   b) If stack is not empty, then find length of current valid
      substring by taking difference between current index and
      top of the stack. If current length is more than result,
      then update the result.
   c) If stack is empty, push current index as base for next
      valid substring.

3) Return result
Explanation with example:
Input: str = "(()()"

Initialize result as 0 and stack with one item -1.

For i = 0, str[0] = '(', we push 0 in stack

For i = 1, str[1] = '(', we push 1 in stack

For i = 2, str[2] = ')', currently stack has [-1, 0, 1], we pop
from the stack and the stack now is [-1, 0] and length of current
valid substring becomes 2 (we get this 2 by subtracting stack top 
from current index).
Since current length is more than current result, we update result.

For i = 3, str[3] = '(', we push again, stack is [-1, 0, 3].

For i = 4, str[4] = ')', we pop from the stack, stack becomes 
[-1, 0] and length of current valid substring becomes 4 (we get 
this 4 by subtracting stack top from current index). 
Since current length is more than current result, we update result.

Comments

Popular Posts

TARUNKUMAR RAWAT:Fourier Series and Fourier Transform

Tarunkumar Rawat Fourier Series: Click here to download Tarun Rawat Fourier Series Tarunkumar Rawat Fourier Transform: Click here to download TarunRawat Fourier Transform Steps to follow: 1) Click on the above link 2) Wait for 3 secs and click on the link 3) Wait for 5 secs and click on skip ad NOTE: We do require these ads to fund the site and provide books for free. Besides these are harmless and just require 5 secs waiting and nothing else. Please be patient for 5 secs and get your desired book for FREE!  IMPORTANT: We believe that every author deserves some respect and the same should be shown towards them by purchasing the books and lauding the efforts of author. Hence we recommend to buy the book. You can buy the book for an affordable rate in given below link: Using of PDF will be at your own risk and EXTC RESOURCES IS NOT RESPONSIBLE for any consequences of the same. We provide links for book and donot endorse piracy.  

Modern Digital and Analog Communication (BP Lathi,3rd ed)

Another Analog communication book: Modern Digital and Analog Communication (BP Lathi,3rd ed) : Click here to download Modern Digital and Analog Communication (BP Lathi,3rd ed) Copyright Disclaimer: This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.

Numerical methods with MATLAB

For Numerical methods along with MATLAB the best book is: Chapra Applied Numerical Methods MATLAB Engineers Scientists 3rd edition : Click here to download Steven Chapra with MATLAB For altenate link : Click here to download Steen Chapra with MATLAB