valid-parenthesis-string
Problem
Problem Description
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:
Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('.
Left parenthesis '(' must go before the corresponding right parenthesis ')'.
'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
An empty string is also valid.
Example 1:
Input: "()"
Output: True
Example 2:
Input: "(*)"
Output: True
Example 3:
Input: "(*))"
Output: True
Note:
The string size will be in the range [1, 100].Solution
For valid parenthesis problem, left parenthesis must equal to right parenthesis, and left must be before right parenthesis.
in this problem, add one more character *, can be left parenthesis, or empty, or right parenthesis.
Need to consider one case, that all ) have matches, and only ( and * position, for example, "**((*" invalid, * position is in the left of (.
Record
((left) and*(star) counts and index.when encounter
), check(and*counts,if
left.count == 0 && star.count == 0, means current)is left most parenthesis,nothing matches, return false;
if
left.count > 0, then left.count--;if
left.count == 0, then star.count--;
when encounter
(, add left.count++, left.index=i (current index).when encounter
*, add star.count++, star.index=i (current index).after iterate through String
s, checkif left.count > star.count, return false. (no enough
*to match().iterate
(, if left.index > star.index, return false (*in left of(, not match, i.e. "*("))after compare all
(and*index, return true
return true.
For example:

Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(N)
N - the length of String s
Code
iterative solution
recursive solution
Last updated
Was this helpful?