LeetCode 670. Maximum Swap 字符串有坑

Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1:

Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.

Example 2:

Input: 9973
Output: 9973
Explanation: No swap.

 

Note:

  1. The given number is in the range [0, 108]

-----------------------

 從前向後,從大到小,找比自己大的字符,如果找到了,把最靠後的位和當前位交換:

class Solution(object):
    def maximumSwap(self, num):
        A = list(str(num))
        last = {x: i for i, x in enumerate(A)}
        print(last)
        for i in range(len(A)):
            for d in sorted(last.keys(), reverse=True):
                if last[d] > i and d>A[i]:
                    A[i], A[last[d]] = A[last[d]], A[i]
                    return int("".join(A))
        return num

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章