在 Python 中查找回文时间,且该时间在给定时间之后

pythonserver side programmingprogramming更新于 2025/10/16 3:56:17

假设我们有一个字符串 s,它以 HH:MM 格式表示 24 小时制时间,因此 HH 的范围为 0 到 23,MM 的范围为 0 到 59,我们必须找到下一个最接近的回文时间,当将其读作字符串时,该时间就是回文时间。如果没有这样的字符串,则返回 -1。

因此,如果输入为"22:22",则输出为"23:32"。

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

  • n := s 的大小

  • hour_string := s 的子字符串[从索引 0 到 2]

  • minute := s 的子字符串[从索引 3 到 5]并将其转换为整数

  • rev_hour := 反转 hour_string 并将其转换为数字

  • rev_hr_str := hour_string 的反转

  • h := hour_string as整数

  • temp := 空字符串,res := 空字符串

  • 如果 h 为 23 且分钟 >= 32,则

    • res := -1

  • 否则,当分钟 < rev_hour 时,则

    • 如果 h < 10,则

      • temp := "0"

    • temp := temp 连接 h

    • 如果 rev_hour < 10,则

      • res := res 连接临时字符串 连接 ":0" 连接 rev_hr_str

    • 否则,

      • res := res 连接临时字符串 连接 ":" 连接 rev_hr_str

  • 否则,

    • h := h + 1

    • rev_hr_str := 字符串的反转

    • rev_hour := h 的反转

    • 如果 h < 10,则

      • temp := "0"

    • temp := temp 连接 h

    • 如果 rev_hour < 10,则

      • res := res 连接 temp 连接 ":0" 连接 rev_hr_str

    • 否则,

      • res := res 连接 temp 连接 ":" 连接 rev_hr_str

  • 返回 res

示例

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

def get_next_palindrome_time(s) :
   n = len(s)
   hour_string = s[0 : 2]
   minute = int(s[3 : 5])
   rev_hour = int(hour_string[::-1])
   rev_hr_str = hour_string[::-1]
   h = int(hour_string)
   temp = ""
   res = ""
   if (h == 23 and minute >= 32) :
      res = "-1"
   elif (minute < rev_hour) :
      if (h < 10) :
         temp = "0"
      temp = temp + str(h)
      if (rev_hour < 10) :
         res = res + temp + ":0" + rev_hr_str
      else :
         res = res + temp + ":" + rev_hr_str
   else :
      h += 1
      rev_hr_str = str(h)[::-1]
      rev_hour = int(rev_hr_str)
      if (h < 10) :
         temp = "0"
      temp = temp + str(h)
      if (rev_hour < 10) :
         res = res + temp + ":0" + rev_hr_str
      else :
         res = res + temp + ":" + rev_hr_str
return res
s = "22:22"
print(get_next_palindrome_time(s))

输入

"22:22"

输出

23:32

相关文章


有用资源