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:
- The input n is a positive integer represented by string, whose length will not exceed 18.
- 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
- 564. Find the Closest Palindrome
- 564. Find the Closest Palindrome
- 564. Find the Closest Palindrome (Hard)
- leetcode 564. Find the Closest Palindrome
- leetcode 564. Find the Closest Palindrome(java)
- [Leetcode] 564. Find the Closest Palindrome 解题报告
- [LeetCode] 564. Find the Closest Palindrome 深入浅出讲解和代码示例
- leetcode 564. Find the Closest Palindrome 距离自己最近的回文数字
- LeetCode 564: Find the Closest Palindrome(python)
- Find the Closest Palindrome:寻找与给定目标大小最接近且尽可能小的回文
- NOJ [1251] Find the Palindrome
- hdu3068 Manacher --> find the longest palindrome
- Find K Closest Elements
- 寻找最近点对问题(FCPP find the closest pair of point)
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- The Closest M Points
- JAVA常见异常整理
- 算法系列之--Javascript和Kotlin的基数排序算法(原)
- css居中
- 步进电机加编码器就是伺服电机吗
- android中WebView与JS的交互
- 564. Find the Closest Palindrome
- iOS 11 安全区域适配总结(转)
- MFC将一个位图添加到数据库中并且将其读出来到指定的Picture控件上
- Cocos Creator 实现按钮图标的流光特效(Shader)
- 机房运维的一些目前对竞价商城防御DDOS攻击处理方案
- Android标题栏ToolBar详解
- Leetcode问题解答:4. Median of Two Sorted Arrays
- 1.TensorFlow初识 TF实现线性回归模型
- JAVA获取当前系统时间System.currentTimeMillis()