Re: [闲聊] 每日leetcode

楼主: dont   2024-08-24 10:06:20
564. Find the Closest Palindrome
## 思路
回文就把前半数字复制到后半
因为有多种case, 所以产生所有可能case的回文
取跟原数字差值最小的回文
1. 一般case: 12345 -> 12321
2. 加减位数: 99 -> 101, 1000 -> 999
3. 位数不变, 但中间值-1: 9500 -> 9449
4. 11~15 -> 9
吃了几个WA 烦
## Code
```python
class Solution:
def nearestPalindromic(self, n: str) -> str:
if len(n) == 1:
return str(int(n)-1)
def get_palindrome(s):
res = list(s)
m = len(s)//2
for i in range(m):
res[~i] = res[i]
# corner case: n is palindromic
output = ''.join(res)
if output != n:
return output
# 12021 -> 12121
if len(res) & 1:
res[m] = str(int(res[m])-1) if res[m] != '0' else
str(int(res[m])+1)
else:
res[m-1] = res[m] = str(int(res[m])-1) if res[m] != '0' else
str(int(res[m])+1)
return ''.join(res)
m = len(n)//2
n1 = str(int(n) + 10**m) # 99 -> 101
n2 = str(int(n) - 10**m) # 9500 -> 9449
n3 = str(int(n) - 10**(m-1)) # 1000 -> 999
res = ''
curr_min = float('inf')
for s in n2, n3, n, n1:
palindrome = get_palindrome(s) if len(s) > 1 else '9'
diff = abs(int(palindrome) - int(n))
if diff < curr_min:
curr_min = diff
res = palindrome
return res
```

Links booklink

Contact Us: admin [ a t ] ucptt.com