Top MNC interview question which will be very useful for beginners to crack the interview and for there future careers

test

Breaking

Post Top Ad

Your Ad Spot

Sunday, December 27, 2020

Length of the longest valid substring(Google Interview Questions)

 Question:

Length of the longest valid substring

Explanation:

A string consist of opening and closing parenthesis, so we need find the length of the longest valid parenthesis substring.

For Example:

                  str = ((()()()()

                   Result=8 

Program:

def findMaxLen(string):
    n = len(string)
    stack = []
    stack.append(-1)
    result = 0
    for i in range(n):
        if string[i] == '(':
            stack.append(i)
        else:
            if len(stack) != 0:
                stack.pop()
            if len(stack) != 0:
                result = max(result,
                             i - stack[len(stack) - 1])
            else:
                stack.append(i)
    return result

string = "((()()()()"
print(findMaxLen(string))
string = "()(()))))())))"
print(findMaxLen(string))

Post Top Ad

Your Ad Spot