LeetCode 1842. Next Palindrome Using Same Digits
原题链接在这里:https://leetcode.com/problems/next-palindrome-using-same-digits/
题目:
ou 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.
Example 1:
Input: num = "1221" Output: "2112" Explanation: The next palindrome larger than "1221" is "2112".
Example 2:
Input: num = "32123" Output: "" Explanation: No palindromes larger than "32123" can be made by rearranging the digits.
Example 3:
Input: num = "45544554" Output: "54455445" Explanation: The next palindrome larger than "45544554" is "54455445".
Constraints:
1 <= num.length <= 105
num
is a palindrome.
题解:
The original num is a palindorme. For the next bigger using the same element, we could first take its left half.
If the length is odd, like "12321", we only take "12".
Then get next permutation using left half "12" -> "21".
Then use the next permutation + "3" + reverse next permutation.
If we can't find the next permutation, then we return "".
Time Complexity: O(n). n = num.length(). getNextPal takes O(n).
Space: O(n).
AC Java:
1 class Solution { 2 public String nextPalindrome(String num) { 3 if(num == null || num.length() == 0){ 4 return num; 5 } 6 7 int n = num.length(); 8 int [] arr = new int[n / 2]; 9 for(int i = 0; i < arr.length; i++){ 10 arr[i] = num.charAt(i) - '0'; 11 } 12 13 if(!getNextPal(arr)){ 14 return ""; 15 } 16 17 StringBuilder sb = new StringBuilder(); 18 for(int i = 0; i < arr.length; i++){ 19 sb.append(arr[i]); 20 } 21 22 if(n % 2 == 0){ 23 return sb.toString() + sb.reverse().toString(); 24 } 25 26 return sb.toString() + num.charAt(n / 2) + sb.reverse().toString(); 27 } 28 29 private boolean getNextPal(int [] arr){ 30 if(arr == null || arr.length == 0){ 31 return false; 32 } 33 34 int n = arr.length; 35 int i = n - 2; 36 while(i >= 0 && arr[i] >= arr[i + 1]){ 37 i--; 38 } 39 40 if(i < 0){ 41 return false; 42 } 43 44 int j = n - 1; 45 while(j > i && arr[j] <= arr[i]){ 46 j--; 47 } 48 49 swap(arr, i, j); 50 reverse(arr, i + 1, n - 1); 51 return true; 52 } 53 54 private void reverse(int [] arr, int i, int j){ 55 while(i < j){ 56 swap(arr, i++, j--); 57 } 58 } 59 60 private void swap(int [] arr, int i, int j){ 61 int temp = arr[i]; 62 arr[i] = arr[j]; 63 arr[j] = temp; 64 } 65 }