You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros.
Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo109 + 7.
Example 1:
Input: num = "327"
Output: 2
Explanation: You could have written down the numbers:
3, 27
327
Example 2:
Input: num = "094"
Output: 0
Explanation: No numbers can have leading zeros and all numbers must be positive.
Example 3:
Input: num = "0"
Output: 0
Explanation: No numbers can have leading zeros and all numbers must be positive.
Constraints:
1 <= num.length <= 3500
num consists of digits '0' through '9'.
Solutions
Solution 1: Dynamic Programming + Prefix Sum
Thinking
We split the digit string into non-decreasing integers without leading zeros. Exponential cuts become an \(O(n^2)\) DP for \(n\le 3500\).
\(dp[i][j]\) is the number of ways for the first \(i\) digits whose last part has length \(j\). A shorter previous part is always smaller and is added via a prefix sum; equal lengths use an LCP table to compare.
\(dp[i][j]\) also stores that prefix, so the answer is \(dp[n][n]\).
Define \(dp[i][j]\) to represent the number of ways to partition the first \(i\) characters of the string num such that the length of the last number is \(j\). Clearly, the answer is \(\sum_{j=0}^{n} dp[n][j]\). The initial value is \(dp[0][0] = 1\).
For \(dp[i][j]\), the end of the previous number should be \(i-j\). We can enumerate \(dp[i-j][k]\), where \(k \le j\). For the part where \(k < j\), i.e., the number of ways with a length less than \(j\) can be directly added to \(dp[i][j]\), i.e., \(dp[i][j] = \sum_{k=0}^{j-1} dp[i-j][k]\). Because the previous number is shorter, it means it is smaller than the current number. Here, prefix sum can be used for optimization.
However, when \(k = j\), we need to compare the sizes of the two numbers of the same length. If the previous number is larger than the current number, this situation is invalid, and we should not add it to \(dp[i][j]\). Otherwise, we can add it to \(dp[i][j]\). Here, we can preprocess the "longest common prefix" in \(O(n^2)\) time, and then compare the sizes of two numbers of the same length in \(O(1)\) time.
The time complexity is \(O(n^2)\), and the space complexity is \(O(n^2)\). Where \(n\) is the length of the string num.