查找解密字符串的第 k 个字符 - Python 中的 Set – 2

pythonserver side programmingprogramming更新于 2025/10/10 12:28:17

假设我们有一个编码字符串,其中子字符串的重复表示为子字符串后跟子字符串的数量。例如,如果字符串是"pq2rs2"且 k=5,则输出将是"r",这是因为解密字符串是"pqpqrsrs",第 5 个字符是"r"。我们必须记住,加密子字符串的频率可以超过一位数字。

因此,如果输入类似于字符串 ="pq4r2ts3"并且 k = 11,则输出将为 i,因为字符串是 pqpqpqpqrrtststs

为了解决这个问题,我们将遵循以下步骤 −

  • encoded := blank string

  • occurrence := 0, i := 0

  • while i < size of str, do

    • temp := blank string

    • occurrence := 0

  • while i < str 的大小并且 str[i] 是字母表,则执行

    • temp := temp + str[i]

    • i := i + 1

  • while i < str 的大小,并且 str[i] 是数字,则执行

    • occurrence := appearance * 10 + (str[i]) 的 ASCII - ('0') 的 ASCII

    • i := i + 1

  • 对于 j,范围从 1 到 appearance + 1,增加 1,则执行

    • encoded :=coded + temp

  • 如果 appearance 与 0 相同,则

    • encoded :=coded + temp

  • 返回 coded[k - 1]

示例

让我们看看下面的实现以便更好地理解 −

def find_kth_char(str, k):
   encoded = ""
   occurrence = 0
   i = 0
   while i < len(str):
      temp = ""
      occurrence = 0
      while (i < len(str) and ord(str[i]) >= ord('a') and ord(str[i]) <= ord('z')):
         temp += str[i]
         i += 1
      while (i < len(str) and ord(str[i]) >= ord('1') and ord(str[i]) <= ord('9')):
         occurrence = occurrence * 10 + ord(str[i]) - ord('0')
         i += 1
      for j in range(1, occurrence + 1, 1):
         encoded += temp
   if occurrence == 0:
      encoded += temp
   return encoded[k - 1]

str = "pq4r2ts3"
k = 11
print(find_kth_char(str, k))

输入

"pq4r2ts3", 11

输出

t

相关文章


有用资源