Valid Parentheses String

Valid parentheses string with wildcard.

Given a string containing only three types of characters: ‘(‘, ‘)’ and ‘*’.  Write a function to check whether this string is valid.

We define the validity of a string by these rules:

1) Any left parenthesis ‘(‘ must have a corresponding right parenthesis ‘)’.

2) Any right parenthesis ‘)’ must have a corresponding left parenthesis ‘(‘.

3) Left parenthesis ‘(‘ must go before the corresponding right parenthesis ‘)’.

4) ‘*’ could be treated as a single right parenthesis ‘)’ or a single left parenthesis ‘(‘ or an empty string.

An empty string is also valid.

For Example –

Example 1:

Input: ” * ( ) ) “, Output: true

In the first example, To balance this string we need to treat star as opening bracket ( “(“).

Example 2:

Input: ” ( * ) “, Output: true

In this example, The start is treated as empty string.

Valid Parentheses String

This simplest version of this problem is to check balanced parentheses in an expression.

In this question, the tricky part is how we use star(*). We can either use them as a opening bracket, closing bracket or empty string depending on the scenario.

I have also explained this problem using video tutorial.

Programming questions on stack

Valid Parentheses String with star

Valid Parentheses String with Star (*) – Java Code

In this example, I have explained how to solve this problem using two stacks.

The first step is to traverse this string and take one character at a time. In the first stack, we have to push opening bracket and in the second stack we have to push star(*). If the current character is closing bracket then there are three cases we have to consider.

i) If the first stack is not empty, Then pop the element from the first stack.

ii) If the first stack is empty check the second stack. If second stack is not empty, it means in second stack the star is present. We can treat star as opening bracket in that case.

iii) If both the stacks are empty return false.

After this operation, let’s verify that first stack is empty. If it’s empty then it means string is valid. Otherwise we have to check the number of elements present in second stack is sufficient to make this string valid.

The time complexity of this approach is O(n) and it’s space complexity is also O(n).

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.