1416. Restore The Array

87 篇文章 0 订阅

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 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. There can be multiple ways to restore the array.

Return the number of possible array that can be printed as a string s using the mentioned program.

The number of ways could be very large so return it modulo 10^9 + 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]

Example 4:

Input: s = "2020", k = 30
Output: 1
Explanation: The only possible array is [20,20]. [2020] is invalid because 2020 > 30. [2,020] is ivalid because 020 contains leading zeros.

Example 5:

Input: s = "1234567890", k = 90
Output: 34

 

Constraints:

  • 1 <= s.length <= 10^5.
  • s consists of only digits and doesn't contain leading zeros.
  • 1 <= k <= 10^9.

思路:DP

class Solution(object):
    def numberOfArrays(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int
        """
        mod = 10**9+7
        n = len(s)
        a = [int(c) for c in s]
        dp = [0]*n+[1]
        for i in range(n-1, -1, -1):
            num = a[i]
            if num == 0: continue
            j = i+1
            while num<=k and j<n+1:
                dp[i] += dp[j]
                if j<n:
                    num = 10*num+a[j]
                j+=1
            dp[i] %= mod
        return dp[0]

s=Solution()
print(s.numberOfArrays(s = "1000", k = 10000))
print(s.numberOfArrays(s = "1000", k = 10))
print(s.numberOfArrays(s = "1317", k = 2000))
print(s.numberOfArrays(s = "2020", k = 30))
print(s.numberOfArrays(s = "1234567890", k = 90))

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值