leetcode 564. Find the Closest Palindrome

结果到最后都没有调试出来自己的程序,还是用了别人的……

解题思路

这道题目的意思是,给予一个数字,计算与这个数字距离最小的回文字符串(不能是自身),如果有距离相同的话选择最小的那个。
首先考虑回文字符串的字符串根,比如对于1213,字符串根为12,12131的话为121。这时候很明显,如果不是回文字符串的话,查找回文根的自身、大1位和小1位,肯定有一个是对的(因为不知道哪一个)
除此之外的还有4种特殊情况,都是由于退位引起的,所以进行枚举。

例程

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
#include <queue>
using namespace std;


class Solution {
public:
 // There are only 7 canddiates we need to check
    // time: O(1), space: O(1)
    string nearestPalindromic(string n) {
        int len = n.size();
        if(len == 1) return to_string(stoi(n)-1); // corner case

        // possible candidates 998 -> 999; 1003 -> 1001; 100 -> 99
        vector<long> candidates = {pow(10, len) - 1, pow(10, len - 1) - 1, pow(10, len) + 1, pow(10, len - 1) + 1};

        // Get other candidates
        int halfLen = (len + 1) / 2;
        long prefix = stol(n.substr(0, halfLen));
        vector<long> val = {prefix - 1, prefix, prefix + 1}; // other candidates must be prefix {-1, +0, +1} + reverse(prefix)
        for(long v: val){
            string postfix = to_string(v);
            if(n.size() % 2 == 1) postfix.pop_back(); // If the total length is odd number, pop the middle number in postfix
            reverse(postfix.begin(), postfix.end());
            string candidate = to_string(v) + postfix;
            candidates.push_back(stol(candidate));
        }

        long res = LONG_MAX;
        long num = stol(n);
        int minDis = INT_MAX;
        for(long c: candidates){
            if(c == num) continue;
            if(labs(c - num) < minDis){
                minDis = labs(c - num);
                res = c;
            }
            else if(labs(c - num) == minDis && c < res)
                res = c;

        }
        return to_string(res);
    }
};
/*
最近回文字符串
    给定一个只含有0-9的字符串,返回其最近回文字符串
    如果距离相等,以前面为标准进行转换
    如果不是回文串,则找到一个回文串
    如果是回文串,找到与其距离最近的回文串

    有三种情况:
        root
        root-1
        root+1
        用这三个来合成,计算除了相等之外差距最小的那个,然后返回
*/
int main(void)
{
    Solution s;
    cout<<s.nearestPalindromic("1213")<<endl;
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值