⭐️⭐️⭐️
# 題目敘述
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s
and all we know is that all integers in the array were in the range [1, k]
and there are no leading zeros in the array.
Given the string s
and the integer k
, return the number of the possible arrays that can be printed as s
using the mentioned program. Since the answer may be very large, return it modulo 1e9 + 7
.
# Example 1
Input: s = “1000”, k = 10000
Output: 1
Explanation: The only possible array is [1000]
# Example 2
Input: s = “1000”, k = 10
Output: 0
Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.
# Example 3
Input: s = “1317”, k = 2000
Output: 8
Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]
# 解題思路
Let dp[i]
denote the number of ways to partition the substring s[i:n]
into valid numbers. The base case is dp[n] = 1
, since there is only one way to partition an empty string.
To compute dp[i]
for a given index i
, we consider all possible substrings that can be formed starting from i
, such that the length of the substring is less than or equal to the number of digits in k
. We convert each substring to an integer and check if it is less than or equal to k
. If it is, we add the number of ways to partition the remaining string s[j+1:n]
to dp[i]
, where j
is the index of the last character in the substring. We sum up the values of dp[i]
for all valid substrings to obtain the final value of dp[i]
.
# Solution
class Solution { | |
public: | |
int numberOfArrays(string s, int k) { | |
int n = s.length(); | |
vector<long long> dp(n + 1, 0); | |
dp[n] = 1; | |
for (int i = n - 1; i >= 0; i--) { | |
if (s[i] == '0') { | |
continue; | |
} | |
long long num = 0; | |
int j = i; | |
while (j < n) { | |
try { | |
int x = stoi(s.substr(i, j-i+1)); | |
if (x > k) { | |
break; | |
} | |
num += dp[j+1]; | |
} | |
catch (std::out_of_range& e) { | |
break; | |
} | |
j++; | |
} | |
dp[i] = num % 1000000007; | |
} | |
return dp[0]; | |
} | |
}; |
class Solution: | |
def numberOfArrays(self, s: str, k: int) -> int: | |
n = len(s) | |
dp = [0] * (n + 1) | |
dp[-1] = 1 | |
for i in range(n - 1, -1, -1): | |
if s[i] == '0': | |
continue | |
num = 0 | |
j = i | |
while j < n and int(s[i:j+1]) <= k: | |
num += dp[j+1] | |
j += 1 | |
dp[i] = num % (10 ** 9 + 7) | |
return dp[0] |