publicclassSolution {
publicintnextPermutation(int num) {
char[] digits = String.valueOf(num).toCharArray();
int n = digits.length;
if (n <= 1) return num;
// Step 1: Find the first decreasing element from the endint i = n - 2;
while (i >= 0 && digits[i]>= digits[i + 1]) {
i--;
}
if (i >= 0) { // If there's any element to swap with// Step 2: Find the element just larger than digits[i] to swap withint j = n - 1;
while (j >= 0 && digits[j]<= digits[i]) {
j--;
}
// Step 3: Swap elementschar temp = digits[i];
digits[i]= digits[j];
digits[j]= temp;
}
// Step 4: Reverse the sublist from i + 1 to the end reverse(digits, i + 1, n - 1);
// Convert char array back to integerreturn Integer.parseInt(new String(digits));
}
privatevoidreverse(char[] nums, int start, int end) {
while (start < end) {
char temp = nums[start];
nums[start]= nums[end];
nums[end]= temp;
start++;
end--;
}
}
}
classSolution:
defnextPermutation(self, num: int) -> int:
digits = list(map(int, str(num)))
n = len(digits)
if n <=1:
return num
# Step 1: Find the first decreasing element from the end i = n -2while i >=0and digits[i] >= digits[i +1]:
i -=1if i >=0: # If there's any element to swap with# Step 2: Find the element just larger than digits[i] to swap with j = n -1while j >=0and digits[j] <= digits[i]:
j -=1# Step 3: Swap elements digits[i], digits[j] = digits[j], digits[i]
# Step 4: Reverse the sublist from i + 1 to the end self.reverse(digits, i +1, n -1)
# Convert list of digits back to an integerreturn int(''.join(map(str, digits)))
defreverse(self, nums: List[int], start: int, end: int) ->None:
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start +=1 end -=1