LeetCode 564. Find the Closest Palindrome 锛堟瀯閫狅級

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 564. Find the Closest Palindrome 锛堟瀯閫狅級相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/sub' title='sub'>sub   ret   abs   lse   near   涓ょ   def   long   

棰樻剰锛?/p>

缁欎竴涓暟瀛梟 姹傜n鏈€杩戯紙涓斾笉绛夛級鐨勫洖鏂囦覆 瀛樺湪澶氫釜绛旀杩斿洖鏈€灏忕殑

 

棣栧厛寰堝鏄撴兂鍒?/p>

灏嗘暟瀛楀垎涓轰袱娈碉紝濡?12345 -> 123/45锛岀劧鍚庡皢鍚庡崐娈垫牴鎹墠闈㈢殑杩涜闀滃儚閲嶇疆 123/45 -> 12321

閭o紝濡傛灉鏁板瓧鍒氬ソ鏄洖鏂囦覆锛屽氨鎶婂墠鍗婃-1灏卞ソ浜?/p>

 

浣嗘槸瀛樺湪浠ヤ笅渚嬪锛屽氨鏄綋鍓嶅崐娈?+1 鎴?-1 灏变細閫犳垚杩涗綅

10999

10901-10999 = -98

11011 - 10999 = -12

鍙互鍙戠幇鏄洜涓?瀛樺湪鐨勮繘浣嶏紝鍚屾牱0涔熷彲鑳斤紝鎵€浠ュ鍓嶅崐娈佃繘琛?+1 鍜?-1 涓ょ澶勭悊锛岀劧鍚庨€夋嫨宸瘮杈冨皬鐨勯偅涓€?/p>

 

浠g爜鍐欑殑姣旇緝涔? =

class Solution {
public:
    string nearestPalindromic(string n) {
        typedef long long ll;
        if (n == "10" || n == "11") return "9";
        
        int l = n.size();
        int half = (l + 1) / 2;
        string left = n.substr(0, half);
        string right = n.substr(half);
        
        // 鎯呭喌1: 鐩存帴闀滃儚缈昏浆
        string ans1 = (l & 1) ? left + rev_str(left).substr(1) : left + rev_str(left);
        // 濡傛灉鍜屽師鏁板瓧鐩稿悓鍒欎笉鍙敤
        ll diff1 = ans1 == n ? stoll(n) : abs(stoll(ans1) - stoll(n));
        
        // 鎯呭喌2: -1
        string left_sub_1 = to_string(stoll(left) - 1);
        string rleft_sub_1 = rev_str(left_sub_1);
        string ans2;
        if (left_sub_1.size() < half) {
            ans2 = (l & 1)
                ? left_sub_1 + rleft_sub_1
                : left_sub_1 + "9" + rleft_sub_1;
        }
        else {
            ans2 = (l & 1)
                ? left_sub_1 + rleft_sub_1.substr(1)
                : left_sub_1 + rleft_sub_1;
        }
        ll diff2 = abs(stoll(ans2) - stoll(n));
        
        // 鎯呭喌3: +1
        string left_add_1 = to_string(stoll(left) + 1);
        string rleft_add_1 = rev_str(left_add_1);
        string ans3;
        if (left_add_1.size() > half) {
            ans3 = (l & 1) 
                ? left_add_1 + rleft_add_1.substr(2) 
                : left_add_1 + rleft_add_1.substr(1);
        }
        else {
            ans3 = (l & 1)
                ? left_add_1 + rleft_add_1.substr(1)
                : left_add_1 + rleft_add_1;
        }
        ll diff3 = abs(stoll(ans3) - stoll(n));
        
        if (diff2 <= diff1 && diff2 <= diff3) return ans2;
        if (diff1 <= diff2 && diff1 <= diff3) return ans1;
        return ans3;
    }
    
    string rev_str(string a) {
        string b(a);
        reverse(b.begin(), b.end());
        return b;
    }
};

 

以上是关于LeetCode 564. Find the Closest Palindrome 锛堟瀯閫狅級的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 564. Find the Closest Palindrome 锛堟瀯閫狅級

564. 寻找最近的回文数

#Leetcode# 997. Find the Town Judge

LeetCode: Find the Duplicate Number

LeetCode 997. Find the Town Judge

Leetcode: Find the Difference