|
| 1 | +# 564. Find the Closest Palindrome |
| 2 | + |
| 3 | +**<font color=red>难度: Hard</font>** |
| 4 | + |
| 5 | +## 刷题内容 |
| 6 | + |
| 7 | +> 原题连接 |
| 8 | + |
| 9 | +* https://leetcode.com/problems/find-the-closest-palindrome/description/ |
| 10 | + |
| 11 | +> 内容描述 |
| 12 | + |
| 13 | +``` |
| 14 | +Given an integer n, find the closest integer (not including itself), which is a palindrome. |
| 15 | + |
| 16 | +The 'closest' is defined as absolute difference minimized between two integers. |
| 17 | + |
| 18 | +Example 1: |
| 19 | +Input: "123" |
| 20 | +Output: "121" |
| 21 | +Note: |
| 22 | +The input n is a positive integer represented by string, whose length will not exceed 18. |
| 23 | +If there is a tie, return the smaller one as answer. |
| 24 | +``` |
| 25 | + |
| 26 | +## 解题方案 |
| 27 | + |
| 28 | +> 思路 1 |
| 29 | +******- 时间复杂度: O(N)******- 空间复杂度: O(N)****** |
| 30 | + |
| 31 | +前前后后搞了2天,感谢今天下午女朋友和我一起讨论,最终搞出来了。 |
| 32 | + |
| 33 | +总共三种情况,算出后面的,前面的,还有当前的前半部分直接反转黏贴到后半部分。 |
| 34 | + |
| 35 | +三个部分看看哪个更近,唯一需要注意的是输入为10和11的时候handle不了,要在最前面手动处理一下。 |
| 36 | + |
| 37 | +beats 100%,功夫不负有心人! |
| 38 | + |
| 39 | +```python |
| 40 | +class Solution(object): |
| 41 | + def nearestPalindromic(self, n): |
| 42 | + """ |
| 43 | + :type n: str |
| 44 | + :rtype: str |
| 45 | + """ |
| 46 | + tmp = str(n) |
| 47 | + if 9 < int(n) < 12: |
| 48 | + return '9' |
| 49 | + r_half_len = len(tmp) // 2 |
| 50 | + if len(tmp) & 1 == 0: |
| 51 | + num_digits = len(str(int(tmp[:len(tmp)/2]))) |
| 52 | + half = tmp[:len(tmp)/2] |
| 53 | + else: |
| 54 | + num_digits = len(str(int(tmp[:(len(tmp)+1)/2]))) |
| 55 | + half = tmp[:(len(tmp)+1)/2] |
| 56 | + |
| 57 | + if len(str(int(half)+1)) > num_digits: |
| 58 | + behind = '1' + '0' * (len(tmp)-1) + '1' |
| 59 | + else: |
| 60 | + behind = str(int(half) + 1)[:r_half_len] + str(int(half) + 1)[r_half_len:]+ str(int(half) + 1)[:r_half_len][::-1] |
| 61 | + if len(str(int(half)-1)) < num_digits: |
| 62 | + before = '9' * (len(tmp)-1) |
| 63 | + else: |
| 64 | + before = str(int(half) - 1)[:r_half_len] + str(int(half) - 1)[r_half_len:]+ str(int(half) - 1)[:r_half_len][::-1] |
| 65 | + |
| 66 | + cur = str(int(half))[:r_half_len] + str(int(half))[r_half_len:]+ str(int(half))[:r_half_len][::-1] |
| 67 | + if cur == tmp[::-1]: |
| 68 | + return behind if abs(int(tmp)-int(behind)) < abs(int(tmp)-int(before)) else before |
| 69 | + abss = map(lambda x: abs(int(x)-int(tmp)), [before, cur, behind]) |
| 70 | + selects = [before, cur, behind] |
| 71 | + return selects[abss.index(min(abss))] |
| 72 | +``` |
0 commit comments