Leetcode 3720. Lexicographically Smallest Permutation Greater Than Target

1. 解题思路

这一题就是一个栈的问题,我们顺序考察每一个位置上能取到的最小的字符,然后看看是否能够组成满足条件的最小字符串即可。

2. 代码实现

给出python代码实现如下:

class Solution:
    def lexGreaterPermutation(self, s: str, target: str) -> str:
        n = len(s)
        src, tgt = Counter(s), Counter(target)

        def dfs(idx):
            nonlocal src, tgt
            if idx == n-1:
                print(src, tgt)
                r, t = list(src.keys())[0], list(tgt.keys())[0]
                if r > t:
                    src.pop(r)
                    tgt.pop(t)
                    return r
                else:
                    return ""
            elif max(src.keys()) <= min(tgt.keys()):
                return ""
            t = target[idx]
            candi = sorted([ch for ch in src.keys() if ch >= t])
            if len(candi) == 0:
                return ""
            elif t == candi[0]:
                src[t] -= 1
                if src[t] == 0:
                    src.pop(t)
                tgt[t] -= 1
                if tgt[t] == 0:
                    tgt.pop(t)
                remain = dfs(idx+1)
                src[t] = 1 if t not in src else src[t]+1
                tgt[t] = 1 if t not in tgt else tgt[t]+1
                if remain != "":
                    return t + remain
                elif len(candi) == 1:
                    return ""
                else:
                    candi = candi[1]
            else:
                candi = candi[0]
            src[candi] -= 1
            remain = ""
            for ch in string.ascii_lowercase:
                remain += ch * src[ch]
            src[ch] += 1
            return candi + remain

        ans = dfs(0)
        return ans

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值