Example 1
- Input
- s = "(*))"
- Output
- true
Assign the star to an opening bracket. The resulting (()) has prefix balances 1, 2, 1, 0, all nonnegative and ending at zero.
You are given a string of opening brackets, closing brackets and stars, where each star may act as an opening bracket, a closing bracket, or nothing at all. Return whether some choice for every star makes the whole bracket sequence balanced.
Given a string s containing only (, ) and *, determine whether s can be a valid parenthesis string, where each * may be treated as (, as ), or as an empty string.
A string is valid when every ( is closed by a later ) with correct nesting. Return true if some assignment of all stars achieves this, otherwise return false.
(, ), or *.Assign the star to an opening bracket. The resulting (()) has prefix balances 1, 2, 1, 0, all nonnegative and ending at zero.
The opening bracket at index 0 is closed at index 1. No wildcard choice is needed, and the final balance is zero.
The star must be empty: assigning either bracket leaves a length-three sequence that cannot balance. Removing it leaves ().
At the minimum input length, the only successful choice is an empty star, producing the valid empty sequence.
The final opening bracket has no later character that can close it. An earlier star cannot serve as a closing bracket for a later opening bracket.
The first character closes a bracket before any opening is available. No assignment to a later star can repair that invalid prefix.
A balanced sequence never closes more brackets than it has opened, and finishes with no unmatched opens. A star can change that running balance by +1, -1, or 0. For Example 1, "(*))", using the star as an opening bracket gives "(())". Instead of committing to one interpretation too soon, keep every feasible prefix balance, then ask whether zero remains feasible at the end.
Reveal Memoized Recursion: intuition, complexity, and code
) lowers both bounds and a * lowers the low bound while raising the high bound; clamp a negative low bound to zero and fail fast on a negative high bound.* and an all-star string are valid by making every star empty.")*", fails immediately; later stars cannot fix its prefix."*(", the star appears too early to close the final opening. Ordering matters even when total counts could match."(*)", the star must be empty, so checking only its bracket interpretations loses a valid solution.")*". Reject negative high first."*" even though an empty assignment works. Test whether zero is feasible, using low == 0.When one symbol fans out into many possibilities, tracking the whole interval of reachable balances replaces exponential branching with two running numbers.