564-Find the Closest Palindrome

kevin聰發表於2018-04-24

Description

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:

  1. The input n is a positive integer represented by string, whose length will not exceed 18.
  2. If there is a tie, return the smaller one as answer.

問題描述

給定整數n, 找出最近的迴文整數(不包括n)
“最近”被定義為兩數之差的絕對值最小


問題分析

最近的迴文存在三種可能性

  1. 直接將字串左半邊取逆覆蓋到右半邊
  2. 一定比n小的迴文
  3. 一定比n大的迴文

如何獲取一定比n小的迴文?
舉兩個例子

  1. n = “10001”, 返回”9999”
  2. n = “10101”, 返回”10001”

如何獲取一定比n大的迴文?
舉兩個例子

  1. n = “9921”, 返回”10001”
  2. n = “9821”, 返回”9921”

整理一下

獲取三種可能的迴文,比較與n的差值的絕對值, 返回最小的那個


解法

public class Solution {
    //將左半邊字串逆序覆蓋到右半邊, 製造迴文的功能函式
    public String mirroring(String s) {
        String x = s.substring(0, (s.length()) / 2);
        return x + (s.length() % 2 == 1 ? s.charAt(s.length() / 2) : "") + new StringBuilder(x).reverse().toString();
    }
    public String nearestPalindromic(String n) {
        if(n.equals("1"))  return "0";
        //a為第一種情況
        String a = mirroring(n);
        long diff1 = Long.MAX_VALUE;
        diff1 = Math.abs(Long.parseLong(n) - Long.parseLong(a));
        //注意, 返回結果不能是n
        if(diff1 == 0)  diff1 = Long.MAX_VALUE;
        //第二種情況
        StringBuilder s = new StringBuilder(n);
        int i = (s.length() - 1) / 2;
        while(i >= 0 && s.charAt(i) == '0'){
            s.replace(i, i + 1, "9");
            i--;
        }
        if(i == 0 && s.charAt(i) == '1'){
            s.delete(0, 1);
            int mid = (s.length() - 1) / 2;
            s.replace(mid, mid + 1, "9");
        }else{
            s.replace(i, i + 1, "" + (char)(s.charAt(i) - 1));
        }

        String b = mirroring(s.toString());
        long diff2 = Math.abs(Long.parseLong(n) - Long.parseLong(b));

        //第三種情況
        s = new StringBuilder(n);
        i = (s.length() - 1) / 2;
        while(i >= 0 && s.charAt(i) == '9'){
            s.replace(i, i + 1, "0");
            i--;
        }
        if(i < 0)   s.insert(0, "1");
        else        s.replace(i, i + 1, "" + (char)(s.charAt(i) + 1));

        String c = mirroring(s.toString());
        long diff3 = Math.abs(Long.parseLong(n) - Long.parseLong(c));
        //比較差值絕對值, 返回最小的那個
        if(diff2 <= diff1 && diff2 <= diff3)    return b;

        if(diff1 <= diff3 && diff1 <= diff2)    return a;
        else    return c;
    }
}

相關文章