LeetCode 564. Find the Closest Palindrome
原题链接在这里:https://leetcode.com/problems/find-the-closest-palindrome/
题目:
Given an integer n, find the closest integer (not including itself), which is a palindrome.
The 'closest' is defined as absolute difference minimized between two integers.
Example 1:
Input: "123" Output: "121"
Note:
- The input n is a positive integer represented by string, whose length will not exceed 18.
- If there is a tie, return the smaller one as answer.
题解:
First find all the candidates, add "9999..999", "10000..0001". say n = "10", its closet palindrome is "9".
Add first half, + reverse of (first half).
e.g. 12567, its first half is 125, the candiates couldbe 12521, 12421, 12621.
Then check all the candidates and find the closest one.
Time Complexity: O(mn). m = is candidates list size. n is candiate length.
Space: O(mn).
AC Java:
1 class Solution { 2 public String nearestPalindromic(String n) { 3 if(n == null || n.length() == 0){ 4 return n; 5 } 6 7 int len = n.length(); 8 int ind = (len + 1) / 2; 9 long left = Long.valueOf(n.substring(0, ind)); 10 List<Long> cans = new ArrayList<>(); 11 boolean isEven = len % 2 == 0; 12 cans.add(getPal(left, isEven)); 13 cans.add(getPal(left + 1, isEven)); 14 cans.add(getPal(left - 1, isEven)); 15 cans.add((long)(Math.pow(10, len - 1) - 1)); 16 cans.add((long)(Math.pow(10, len) + 1)); 17 18 long diff = Long.MAX_VALUE; 19 long res = 0; 20 long original = Long.valueOf(n); 21 for(long can : cans){ 22 if(can == original){ 23 continue; 24 } 25 26 if(Math.abs(can - original) < diff){ 27 diff= Math.abs(can - original); 28 res = can; 29 }else if(Math.abs(can - original) == diff){ 30 res = Math.min(res, can); 31 } 32 } 33 34 return String.valueOf(res); 35 } 36 37 private long getPal(long left, boolean isEven){ 38 long res = left; 39 if(!isEven){ 40 left /= 10; 41 } 42 43 while(left != 0){ 44 res = res * 10 + left % 10; 45 left /= 10; 46 } 47 48 return res; 49 } 50 }