Since the input is already a palindrome, the next palindrome using the same digits must be the next lexicographical permutation of the palindrome. We only need to permute the first half (and possibly the middle digit for odd length) and mirror it to form the palindrome.
#include<algorithm>string nextPalindrome(string num) {
int n = num.size();
int half = n /2;
string left = num.substr(0, half);
string mid = n %2? string(1, num[half]) :"";
if (!next_permutation(left.begin(), left.end())) return"";
string right = left;
reverse(right.begin(), right.end());
string res = left + mid + right;
return res > num ? res : "";
}
funnextPalindrome(num: String): String {
val n = num.length
val half = n / 2val left = num.substring(0, half).toCharArray()
val mid = if (n % 2==1) num[half].toString() else""if (!nextPermutation(left)) return""val right = left.reversed().joinToString("")
val res = left.joinToString("") + mid + right
returnif (res > num) res else""}
funnextPermutation(arr: CharArray): Boolean {
var i = arr.size - 2while (i >=0&& arr[i] >= arr[i+1]) i--if (i < 0) returnfalsevar j = arr.size - 1while (arr[j] <= arr[i]) j-- arr[i] = arr[j].also { arr[j] = arr[i] }
arr.reverse(i+1, arr.size)
returntrue}
funCharArray.reverse(from: Int, to: Int) {
var l = from; var r = to-1while (l < r) {
val tmp = this[l]; this[l] = this[r]; this[r] = tmp
l++; r-- }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
defnextPalindrome(num: str) -> str:
n = len(num)
half = n //2 left = list(num[:half])
mid = num[half] if n %2else''ifnot next_permutation(left): return'' right = left[::-1]
res =''.join(left) + mid +''.join(right)
return res if res > num else''defnext_permutation(arr):
i = len(arr) -2while i >=0and arr[i] >= arr[i+1]: i -=1if i <0: returnFalse j = len(arr) -1while arr[j] <= arr[i]: j -=1 arr[i], arr[j] = arr[j], arr[i]
arr[i+1:] = reversed(arr[i+1:])
returnTrue