【leetcode】564. Find the Closest Palindrome

题目如下:

解题思路:既然是要求回文字符串,那么最终的输出结果就是对称的。要变成对称字符串,只要把处于对称位置上对应的两个字符中较大的那个变成较小的那个即可,假设n=1234,1和4对称所以把4变成1,2和3对称把3变成2,得到1221,看起来好像没问题了。可是如果n=1283,按照这个方法得到的结果是1221,而预期的结果应该是1331,所以需要考虑到进位和退位的问题。这就有点复杂了,简单点的方法也有,就是把进位和退位的所有情况都列举出来再做比较,得出差值最小的那个。例如n=1283,按照对称法则得到的结果是1221,再把处于最中间的两个字符22分别进位和退位就可以得到1331和1111。接下来考虑到数量级的进位退位,对于一个四位数的n来说,与其最接近的三位数长度的回文数是999,最接近的五位数长度是10001。所以最后在这五个数字中得出符合题目要求的答案。

代码如下:

class Solution(object):
    def nearestPalindromic(self, n):
        """
        :type n: str
        :rtype: str
        """
        l = list(n)
        low = 0
        high = len(l) - 1
        while low <= high:
            if l[low] != l[high]:
                l[high] = l[low]
            low += 1
            high -= 1

        candidateList = ['1' + '0'*(len(n)-1) + '1','9' * (len(n) - 1),''.join(l)]
        mid = len(l) / 2
        if len(l) % 2 == 0:
            if l[mid] == '0':
                candidateList.append(''.join(l[0:mid - 1] + ['1'] * 2 + l[mid + 1:]))
            elif l[mid] == 9:
                candidateList.append(''.join(l[0:mid - 1] + ['8'] * 2 + l[mid + 1:]))
            else:
                candidateList.append(''.join(l[0:mid - 1] + [str(int(l[mid]) - 1)] * 2 + l[mid + 1:]))
                candidateList.append(''.join(l[0:mid - 1] + [str(int(l[mid]) + 1)] * 2 + l[mid + 1:]))
        else:
            if l[mid] == '0':
                candidateList.append(''.join(l[0:mid] + ['1'] * 1 + l[mid + 1:]))
            elif l[mid] == 9:
                candidateList.append(''.join(l[0:mid] + ['8'] * 1 + l[mid + 1:]))
            else:
                candidateList.append(''.join(l[0:mid] + [str(int(l[mid]) - 1)] * 1 + l[mid + 1:]))
                candidateList.append(''.join(l[0:mid] + [str(int(l[mid]) + 1)] * 1 + l[mid + 1:]))

        res = ''
        mDiff = 0
        for i in candidateList:
            if i == n or i == '':
                continue
            diff = abs(int(n) - int(i))
            if mDiff == 0 or mDiff > diff:
                res = i
                mDiff = diff
            elif mDiff == diff:
                res = str(min(int(res), int(i)))

        return res
原文地址:https://www.cnblogs.com/seyjs/p/9585935.html