678. Valid Parenthesis String
Description
Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
The following rules define a valid string:
- 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"".
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "(*)" Output: true
Example 3:
Input: s = "(*))" Output: true
Constraints:
1 <= s.length <= 100s[i]is'(',')'or'*'.
Solutions
Solution 1: Dynamic Programming
Thinking
* can be a left, right, or empty token. Backtracking three choices is heavy for length \(100\).
Interval DP: \(dp[i][j]\) is whether \(s[i..j]\) is valid. A single * is valid; a longer span is a matching pair around a valid inside, or a split into two valid pieces.
Let dp[i][j] be true if and only if the interval s[i], s[i+1], ..., s[j] can be made valid. Then dp[i][j] is true only if:
s[i]is'*', and the intervals[i+1], s[i+2], ..., s[j]can be made valid;-
or,
s[i]can be made to be'(', and there is somekin[i+1, j]such thats[k]can be made to be')', plus the two intervals cut bys[k](s[i+1: k] and s[k+1: j+1]) can be made valid; -
Time Complexity: \(O(n^3)\), where \(n\) is the length of the string. There are \(O(n^2)\) states corresponding to entries of dp, and we do an average of \(O(n)\) work on each state.
- Space Complexity: \(O(n^2)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
Solution 2: Greedy
Thinking
Cubic DP is more than we need. Scan left treating ( and * as stock for ); scan right treating ) and * as stock for (. Both passes must succeed.
Scan twice, first from left to right to make sure that each of the closing brackets is matched successfully, and second from right to left to make sure that each of the opening brackets is matched successfully.
- Time Complexity: \(O(n)\), where \(n\) is the length of the string.
- Space Complexity: \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |