[LeetCode] Next Palindrome Using Same Digits

1842. Next Palindrome Using Same Digits

You are given a numeric string num, representing a very large palindrome.

Return the smallest palindrome larger than num that can be created by rearranging its digits. If no such palindrome exists, return an empty string “”.

A palindrome is a number that reads the same backward as forward.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
string nextPalindrome(string num) {
string half = num.substr(0, (num.length()) / 2);
next_permutation(begin(half), end(half));

string rev = half;
reverse(begin(rev), end(rev));
char mid = num.length() & 1 ? num[num.length() / 2] : '#';
string res = mid != '#' ? half + mid + rev : half + rev;

for(int i = 0; i < num.length(); i++) {
if(num[i] < res[i]) return res;
else if(num[i] == res[i]) continue;
else return "";
}

return "";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/01/PS/LeetCode/next-palindrome-using-same-digits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.