556. 下一个更大元素 III

exiaohu 于 2022-07-03 发布

题目链接:556. 下一个更大元素 III

模拟。

class Solution:
    MAX_INT_32 = (1 << 31) - 1

    def nextGreaterElement(self, n: int) -> int:
        num = str(n)

        def is_des(v: str) -> bool:
            return ''.join(sorted(v, reverse=True)) == v

        if is_des(num):
            return -1

        for l in range(2, len(num) + 1):
            if not is_des(num[-l:]):
                c = min(filter(lambda c: c > num[-l], num[-l + 1:]))
                ns = sorted(num[-l:])
                ns.remove(c)
                v = int(num[:-l] + ''.join([c] + ns))
                if v <= self.MAX_INT_32:
                    return v
                return -1
        else:
            return -1