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;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章