Python程序检查字符串是否包含连续递减的字符串


假设我们有一个包含一些数字的字符串s,我们需要检查它是否包含连续递减的整数。

因此,如果输入类似于s = "99989796",则输出将为True,因为此字符串包含[99,98,97,96]。

为了解决这个问题,我们将遵循以下步骤:

  • 定义一个函数helper()。这将接受pos和prev_num作为参数。

  • 如果pos等于n,则

    • 返回True

  • num_digits := prev_num的位数

  • 对于范围从num_digits - 1到num_digits的i,执行:

    • 如果s[从索引pos到pos+i-1]以及s[从索引pos到pos+i-1]的数字形式等于prev_num - 1,则

      • 如果helper(pos + i, prev_num - 1)为真,则

      • 返回True

    • 返回False

    • 在主方法中,执行以下操作:

    • n := s的长度

    • 对于范围从1到n/2的商的i,执行:

      • num := s[从索引0到i-1]的数字形式

      • 如果helper(i, num)为真,则

      • 返回True

    • 返回False

让我们看下面的实现以更好地理解:

示例

在线演示

class Solution:
def solve(self, s):
   n = len(s)
   def helper(pos, prev_num):
   if pos == n:
      return True
   num_digits = len(str(prev_num))
   for i in range(num_digits - 1, num_digits + 1):
      if s[pos:pos+i] and int(s[pos:pos+i]) == prev_num - 1:
         if helper(pos + i, prev_num - 1):
            return True
      return False
   for i in range(1, n//2 + 1):
      num = int(s[:i])
   if helper(i, num):
      return True
   return False
ob = Solution()
s = "99989796"
print(ob.solve(s))

输入

"99989796"

输出

True

更新于:2020年10月5日

248 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.