564. Find the Closest Palindrome

564. Find the Closest Palindrome


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:

  1. 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.

方法1:

discussion:https://leetcode.com/problems/find-the-closest-palindrome/discuss/102391/python-simple-with-explanation
grandyang:https://www.cnblogs.com/grandyang/p/6915355.html

思路:

一共只需要比较5个候选者。首先假设给定n的位数是 len,那么候选数字如果和n位数不同,只能是99…999 , 10…01这种形式。比如对于一个三位数,左右边界为[99, 1001],先把这两个数字放进candidates set中。然后考虑和n数位相同的情况,首先确定要改动一定先改动右边,因为这样造成的差值最小。所以相当于左半边翻转然后连接,这里用string(left.rbegin() + (len & 1), left.rend());的写法,也就是len为奇数的情况下复制除了中轴,偶数复制全部。剩下的三个candidates分别是prefix - 1, +0, +1的情况。用prefix = 234来举例,candidates循环中产生23332, 23432, 23532三个候选。最后由于要避免n本身就是palindrome的情况,要将它本身从candidates中删除。最后通过比较和原数字大小来决定最终结果,注意如果差值相同时优先选择较小值。

易错点

  1. 删除n本身。
  2. 如果差值相同时优先选择较小值。
  3. (len & 1)。
class Solution {
public:
    string nearestPalindromic(string n) {
        int len = n.size();
        set<long> candidates;
        candidates.insert(pow(10, len) + 1);
        candidates.insert(pow(10, len - 1) - 1);
        
        long prefix = stol(n.substr(0, (len + 1) / 2));
        for (int i = -1; i <= 1; i++) {
            string left = to_string(prefix + i);
            string rest = string(left.rbegin() + (len & 1), left.rend());
            candidates.insert(stol(left + rest));
        }
        
        candidates.erase(stol(n));
        
        long num = stol(n), minDiff = LONG_MAX, result;
        for (auto a: candidates) {
            long diff = abs(a - num); 
            if (diff < minDiff) {
                result = a;
                minDiff = abs(a - num);
            } 
            else if (diff == minDiff){
                result = min(a, result);
            }
        }
        return to_string(result);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值