Leetcode 670. Maximum Swap

2021-02-04 10:54:55 浏览数 (1)

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

代码语言:javascript复制
class Solution:
    def maximumSwap(self, num):
        s = list(str(num))
        length = len(s)
        if length < 2:
            return num

        for i in range(length - 1):
            max_index = i
            for j in range(i   1, length):
                if s[j] >= s[max_index] and s[i] != s[j]:
                    max_index = j
            if max_index != i:
                temp = s[i]
                s[i] = s[max_index]
                s[max_index] = temp
                break 

        return int(''.join(s))

Reference

  1. https://leetcode.com/problems/maximum-swap/

0 人点赞