Fast but complex Python.


  • 0
    M

    The all possible combinations are generated by DFS, and then choose the closest one.Following is my code.And all suggestions are welcome. :-p

    def nextClosestTime(self, time):
        digits = time[:2] + time[3:]
        res = []
        def dfs(digits, path, res):
            if len(path) == 4:
                res.append(path)
                return
            for i in range(len(digits)):
                dfs(digits, path+digits[i], res)
    
        dfs(digits, '', res)
        closest_time = max(res)
    
        for r in res:
            if r[0] > '2' or r[:2] >= '24' or r[2] >= '6':
                continue
            if digits >= r:
                r = int(r) + 2400
            closest_time = min(str(closest_time), str(r))
    
        if int(closest_time) > int(2400):
            closest_time = str(int(closest_time) - 2400)
        return closest_time[:2] + ':' + closest_time[2:]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.