📜  门| GATE CS 2018 |第 47 题(1)

📅  最后修改于: 2023-12-03 15:42:11.712000             🧑  作者: Mango

题目描述

给定一个字符串S,找到S中的所有非空子序列,使得它们按字典序排列后,第K个子序列是什么。

子序列:一个序列是另一个序列的子序列,当且仅当该序列作为其他序列的一部分而存在,但不必须连续。

注意:输入字符串的长度不超过15,且K ≤ 10^9。

例子

输入:

S = "abc"
K = 4

输出:

"ab"

解法

为了找到第K个子序列,我们需要迭代地选择每个字符或跳过它,直到我们得到K个选择。我们有两个选项:选定当前字符或跳过它。我们可以根据当前结果的大小来跟踪所有子序列。

首先,我们需要计算出S中可能的子序列数,因为如果K大于所有可能的子序列数,我们就可以返回空字符串。有n个字符,所以我们有2^n个子序列。

考虑以下示例输入:

S = "abc"
K = 4

个数减为

n = 3
2^n = 2^3 = 8

现在,我们都准备好了,迭代以下每个字符:

o    a         count = 1
|    |
a -> ab        count = 2
|    |
-> b           count = 3
|    |
     -> bc     count = 4
     |    |
     |    -> c count = 5
     |
        c      count = 6
     |
        bc     count = 7
     |
        b      count = 8
        

我们可以看到,输出字符串是“ab”,它是按字典序排列的第4个字符串

代码

class Solution:
    def getKthSubstring(self, S: str, K: int) -> str:
        n = len(S)
        count = 0
        result = ""
        subsetCount = pow(2, n)
        if K > subsetCount:
            return ""
        for i in range(0, n):
            for j in range(i, n):
                currStr = S[i : j + 1]
                if currStr != "":
                    count += 1
                    if count == K:
                        result = currStr
                        break
            if count == K:
                break
        return result