The answer may be very large so return it modulo ‘10^9 + 7’.
You are given ‘NUM’ = “329”, Here you can split the string as [3, 29] and [329]. Since there are 2 ways the answer will be 2.
Note that a split [32, 9] is invalid because the list is not in non-decreasing order.
The first line of input contains a single integer ‘T’ representing the number of test cases.
The first and only line of each test case contains a string ‘NUM’ representing the string given in the problem.
For each test case print a single integer representing the number of ways you can split the string with the given conditions.
Print a separate line for each test case.
1 <= T <= 10
1 <= NUM.size <= 500
NUM[i] is a digit from 0 to 9
Time Limit: 1 sec
You do not need to print anything. It has already been taken care of. Just implement the given function.
In this approach, we can see that if any string starts with a 0 then it has no was to be separated into a list of non-decreasing positive integers.
Let's imagine we know the number of ways to split characters according to the rules before each position in the string and all possible lengths of the previous part. Then for the next position, the number of ways to split characters from start to this position can be calculated recursively.
And what if we know for each position in the string number of ways to split it into parts no longer than D. Then for D +1 we can calculate it from previous values for each position.
We will create a function ‘checkString(nums, start1, start2, length)’ which will check if the number formed by starting at ‘start1’ index is less than the number formed by starting at the ‘start2’ index, where both are of ‘length’ length
Algorithm:
In this approach, we will use the idea behind the previous approach, which is if we know the number of ways to split characters according to the rules before each position in the string and all possible lengths of the previous part. Then for the next position, the number of ways to split characters from start to this position can be calculated.
Suppose the number of ways to form the list when the last number starts at index ‘i’ and ends at index ‘j’ is ‘dp[i][j]’.
Then ‘dp’ transition is Let length = j-i+1 = length of last number
Thus, we can choose all numbers ending at nums[i-1], and have length < length
=> dp[i][j] += dp[i-length+1][i-1] + ... + dp[i-1][i-1]
Now, if num[i-length : i-1] is smaller or equal to num[i : j]
i.e., if (second last number of length = length) is smaller or equal to last number, then
=> dp[i][j] += dp[i-length][i-1]
This is equal to the previous approach which is O(N ^ 3). To optimise it we Use prefix sum DP to calculate sums fast
Thus, in prefSum[i][j] we store dp[0][j] + dp[1][j] ... + dp[i][j]
We create a compare(i, j, length, same, nums), which will compare two strings fastly (O(1)). This is due to the ‘same’ matrix that stores the length of the common prefix for strings starting at ‘i’ and ‘j’
Algorithm: