Python solution, like next_permutation


  • 0
    B
    class Solution(object):
        def nextGreaterElement(self, n):
            """
            :type n: int
            :rtype: int
            """
            str_val=str(n)
            found=False
            for i in range(len(str_val)-1,0,-1):
                if str_val[i]>str_val[i-1]:
                    found = True
                    break
            if not found: return -1
    
            # find the smallest letter bigger than char i-1 after i-1
            latter=str_val[i:]
            ch=min(ltr for ltr in latter if ltr>str_val[i-1])
    
            ret=str_val[:i-1]+ch
            latter=''.join(sorted(str_val[i:].replace(ch,str_val[i-1],1)))
            ret=int(ret+latter)
            return -1 if ret>0x7FFFFFFF else ret
    

Log in to reply
 

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