Straightforward Python solution with explanation

  • 0
    class Solution(object):
        def maximumSwap(self, num):
            :type num: int
            :rtype: int
            s = str(num)
            max_idx = 0
            max_val = s[0]
            for i,val in enumerate(s):
                if val >= max_val:
                    max_idx = i
                    max_val = val
            if len(s) == 1:
                return int(s)
            elif max_idx != 0 and max_val != s[0]:
                return int(s[max_idx] + s[1:max_idx] + s[0] + s[max_idx + 1:])
                return int(s[0]) * 10**(len(s) - 1) + self.maximumSwap(s[1:])

    First convert int to str.
    Then find the index and value of the maximum of this string.
    If it has only 1 digit then return itself.
    If maximum value is not the first one element's value then switch, or recursively get the the answer.

Log in to reply

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