564. Find the Closest Palindrome

来源:互联网 发布:女生一身淘宝爆款low 编辑:程序博客网 时间:2024/05/19 10:41

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.


思路:

Let's build a list of candidate answers for which the final answer must be one of those candidates. Afterwards, choosing from these candidates is straightforward.

If the final answer has the same number of digits as the input string S, then the answer must be the middle digits + (-1, 0, or 1) flipped into a palindrome. For example, 23456 had middle part 234, and 233, 234, 235 flipped into a palindrome yields 23332, 23432, 23532. Given that we know the number of digits, the prefix 235 (for example) uniquely determines the corresponding palindrome 23532, so all palindromes with larger prefix like 23732 are strictly farther away from S than 23532 >= S.

If the final answer has a different number of digits, it must be of the form 999....999 or 1000...0001, as any palindrome smaller than 99....99 or bigger than 100....001 will be farther away from S.

class Solution(object):    def nearestPalindromic(self, s):        """        :type n: str        :rtype: str        """        k = len(s)        candidates = [str(10**e + d) for e in (k-1, k) for d in (-1, 1)]        prefix = int(s[:int((k+1)/2)])        for start in map(str, (prefix-1, prefix, prefix+1)):            candidates.append(start + (start[:-1] if k%2 else start)[::-1])                def delta(x):            return abs(int(s) - int(x))                ret = None        for t in candidates:            if t != s:                if (ret is None or delta(t)<delta(ret) or delta(t)==delta(ret) and int(t)<int(ret)):                    ret = t                        return ret        


阅读全文
0 0