Number of Unique Good Subsequences LeetCode solution in Java

1
class Solution {
2
public int numberOfUniqueGoodSubsequences(String binary) {
3
int initialZeroCount = 0;
4
while (initialZeroCount < binary.length() && binary.charAt(initialZeroCount) == '0')
5
initialZeroCount++;
6
if (initialZeroCount == binary.length()) return 1;
7
long[] dp = new long[binary.length()];
8
dp[initialZeroCount] = 1;
9
int lastOne = 0, lastZero = 0;
10
long mod = (long) Math.pow(10, 9) + 7;
11
for (int i = initialZeroCount + 1; i < binary.length(); i++) {
12
int j = binary.charAt(i) == '1' ? lastOne : lastZero;
13
long dup = j > 0 ? dp[j - 1] : 0;
14
dp[i] = 2 * dp[i - 1] - dup;
15
if (dp[i] < 0) dp[i] += mod;
16
dp[i] %= mod;
17
if (binary.charAt(i) == '0') lastZero = i;
18
else lastOne = i;
19
}
20

21
int hasZero = 0;
22
if (binary.contains("0")) hasZero = 1;
23

24
return (int) (dp[binary.length() - 1] + hasZero);
25
}
26
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0