You are given a non-empty string S consisting of and There are 2^x ways to obtain a new string by replacing each in S with and where x is the number of occurrences of in S Among them find the n
To solve this problem, we can use dynamic programming. Let's define dp[i][j] as the number of ways to obtain a parenthesis string from the substring S[i:j+1].
We can start by initializing the dp array with all zeros, except for the diagonal where i equals j. In this case, if S[i] is equal to '(', we set dp[i][j] to 1, otherwise we set it to 0.
Then, we can iterate over the length of the substring (l) from 2 to n (length of S). For each l, we iterate over the starting index (i) from 0 to n-l. For each i, we calculate j = i+l-1, which is the ending index.
Inside this nested loop, we check the following conditions:
-
If S[j] is equal to ')', then dp[i][j] is 0 because we cannot have a closing parenthesis without an opening one.
-
If S[i] is equal to '(', then dp[i][j] is 0 because we cannot have an opening parenthesis without a closing one.
-
If S[i] is equal to '?', then we have two possibilities: a. We can replace it with '('. In this case, we add dp[i+1][j] to dp[i][j]. b. We can replace it with ')'. In this case, we add dp[i+1][j] to dp[i][j].
-
If S[j] is equal to '?', then we have two possibilities: a. We can replace it with ')'. In this case, we add dp[i][j-1] to dp[i][j]. b. We can replace it with '('. In this case, we add dp[i][j-1] to dp[i][j].
After iterating through all the substrings, the answer is given by dp[0][n-1] modulo 998244353.
Here is the implementation in Python:
def count_parenthesis(S): n = len(S) dp = [[0] * n for _ in range(n)]
for i in range(n):
if S[i] == '(':
dp[i][i] = 1
for l in range(2, n+1):
for i in range(n-l+1):
j = i + l - 1
if S[j] == ')':
dp[i][j] = 0
if S[i] == '(':
dp[i][j] = 0
if S[i] == '?':
dp[i][j] += dp[i+1][j]
if S[j] == '?':
dp[i][j] += dp[i][j-1]
dp[i][j] %= 998244353
return dp[0][n-1]
Example usage:
S = "((??))" print(count_parenthesis(S)
原文地址: http://www.cveoy.top/t/topic/inLX 著作权归作者所有。请勿转载和采集!