结果到最后都没有调试出来自己的程序,还是用了别人的……
解题思路
这道题目的意思是,给予一个数字,计算与这个数字距离最小的回文字符串(不能是自身),如果有距离相同的话选择最小的那个。
首先考虑回文字符串的字符串根,比如对于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;
}