LeetCode 题解工作台
寻找最近的回文数
给定一个表示整数的字符串 n ,返回与它最近的回文整数(不包括自身)。如果不止一个,返回较小的那个。 “最近的”定义为两个整数 差的绝对值 最小。 示例 1: 输入: n = "123" 输出: "121" 示例 2: 输入: n = "1" 输出: "0" 解释: 0 和 2是最近的回文,但我们返…
2
题型
5
代码语言
3
相关题
当前训练重点
困难 · 数学·string
答案摘要
class Solution: def nearestPalindromic(self, n: str) -> str:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
给定一个表示整数的字符串 n ,返回与它最近的回文整数(不包括自身)。如果不止一个,返回较小的那个。
“最近的”定义为两个整数差的绝对值最小。
示例 1:
输入: n = "123" 输出: "121"
示例 2:
输入: n = "1" 输出: "0" 解释: 0 和 2是最近的回文,但我们返回最小的,也就是 0。
提示:
1 <= n.length <= 18n只由数字组成n不含前导 0n代表在[1, 1018 - 1]范围内的整数
解题思路
方法一
class Solution:
def nearestPalindromic(self, n: str) -> str:
x = int(n)
l = len(n)
res = {10 ** (l - 1) - 1, 10**l + 1}
left = int(n[: (l + 1) >> 1])
for i in range(left - 1, left + 2):
j = i if l % 2 == 0 else i // 10
while j:
i = i * 10 + j % 10
j //= 10
res.add(i)
res.discard(x)
ans = -1
for t in res:
if (
ans == -1
or abs(t - x) < abs(ans - x)
or (abs(t - x) == abs(ans - x) and t < ans)
):
ans = t
return str(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n \cdot log(m)) where n is the length of the string and m is the numeric value used for adjustments. Space complexity is O(n) to store candidate strings and mirrored computations. |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Check if a brute force approach will scale for n up to 10^18.
- question_mark
Consider how string manipulation can generate palindromes instead of numeric iteration.
- question_mark
Ask about tie-breaking rules when multiple palindromes are equally close.
常见陷阱
外企场景- error
Failing to exclude the input number itself when generating closest palindromes.
- error
Overlooking edge palindromes like 10^k + 1 or 10^(k-1) - 1 which are crucial for very small or large n.
- error
Incorrect tie-breaking logic that returns the larger palindrome instead of the smaller one.
进阶变体
外企场景- arrow_right_alt
Find the closest palindrome larger than the given number.
- arrow_right_alt
Find the closest palindrome smaller than the given number.
- arrow_right_alt
Count the number of palindromes within a given numeric range.