Leetcode 3646. Next Special Palindrome Number

1. 解题思路

这一题我的思路的话就是首先计算出所有 1 0 17 10^{17} 1017以下的所有满足条件的特殊回文数字,然后根据具体的 n n n进行查找即可。

而要涉及如何获取所有 1 0 17 10^{17} 1017以下的特殊回文数字,我们就是使用一个迭代的算法即可,我们只要考察每一个数字的使用情况,然后考察单侧的可能排序方法,然后将其返回即可。

2. 代码实现

给出python代码实现如下:

def get_special_palindrome():
    even = [2, 4, 6, 8]
    odd = [1, 3, 5, 7, 9]
    ans = set()

    def get_candidates(idx, candidates):
        nonlocal ans
        if len(candidates) > 8:
            return
        if idx < 4:
            get_candidates(idx+1, candidates)
            get_candidates(idx+1, candidates + [even[idx]] * (even[idx]//2))
        else:
            if len(candidates) > 0:
                for purb in permutations(candidates):
                    sub = "".join([str(x) for x in purb])
                    ans.add(int(sub + sub[::-1]))
            for num in odd:
                dup = [str(num)] * (num//2)
                candi = candidates + dup
                if len(candi) > 8:
                    break
                for purb in permutations(candi):
                    sub = "".join([str(x) for x in purb])
                    ans.add(int(sub + str(num) + sub[::-1]))
        return

    get_candidates(0, [])
    return sorted(ans)

SPECIAL_PALINDROME = get_special_palindrome()

class Solution:
    def specialPalindrome(self, n: int) -> int:
        idx = bisect.bisect_right(SPECIAL_PALINDROME, n)
        return SPECIAL_PALINDROME[idx]

提交代码评测得到:耗时0ms,占用内存18.36MB。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值