Python程式:利用給定時間數字查詢最近時間


假設我們有一個24小時制的時間字串,格式為“hh:mm”,我們需要找到下一個最接近的時間,該時間可以使用給定數字重新組合而成。我們可以隨意多次重複使用給定字串中的數字。

例如,如果輸入s = "03:15",則輸出為03:30,因為這是最接近且重複使用給定數字的時間。

為了解決這個問題,我們將遵循以下步驟:

  • use := 一個包含兩位數小時和兩位數分鐘值的列表
  • possible := 一個新的集合
  • 定義一個函式backtrack()。它將接收path作為引數。
  • 如果path的長度等於4,則
    • 將(path的前兩位數連線":"連線path的後兩位數)插入到possible中。
    • 返回
  • 對於use中的每個p:
    • 如果(path長度為0且p > "2")為假,且(path等於"2"且p > "3")為假,且(path長度為2且p > "5")為假,則
      • backtrack(path + p)
  • 在主方法中執行以下操作:
  • backtrack(空字串)
  • possible := 從possible建立的新列表
  • 對列表possible進行排序
  • 對於範圍0到possible長度-2中的每個i:
    • 如果possible[i]等於s,則
      • 返回possible[i + 1]
  • 返回possible[0]

讓我們來看下面的實現,以便更好地理解。

示例

線上演示

class Solution:
   def solve(self, s):
      use = [s[0], s[1], s[3], s[4]]
      possible = set()

      def backtrack(path):
         nonlocal possible, use
         if len(path) == 4:
            possible.add(path[:2] + ":" + path[2:])
            return
         for p in use:
            if (not (len(path) == 0 and p > "2") and not (path == "2" and p > "3") and not (len(path) == 2 and p > "5")):
backtrack(path + p)

         backtrack("")
         possible = list(possible)
         possible.sort()
         for i in range(len(possible) - 1):
            if possible[i] == s:
               return possible[i + 1]
         return possible[0]

ob = Solution()
s = "03:15"
print(ob.solve(s))

輸入

"03:15"

輸出

03:30

更新於:2020年11月26日

279 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.