Two-pass Scan (T2R & R2T)
1 | class Solution { |
Remarks:
TC: $O(2n)$ or $O(n)$, SC: $O(1)$
Why Two pass?
Example:
((), left to right: 0, right to left: 1*2L2R: left should always be equal or more than right parenthesis; R2L: right should always be equal or more than left parenthesis.
Stack
1 | class Solution { |
Remarks:
- TC: $O(n)$, SC: $O(n)$
Dynamic Programming
1 | class Solution { |
Remarks:
Base:
dp[0]=0if
s[i] == ')'and last ones[i-1]=='('thendp[i] = dp[i-2] + 2if
s[i] == ')'and last ones[i-1]==')'then checks[i - dp[i-1] - 1],dp[i] = dp[i-1] + 2 + dp[i- dp[i-1] -2]