valid-parenthesis-string
Problem
Problem Description
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