在 Python 中索引处解码字符串

pythonserver side programmingprogramming

假设给定一个编码字符串 S。我们必须找到并将解码后的字符串写入磁带,这里一次读取一个字符的编码字符串,并执行以下步骤 −

  • 如果读取的字符是字母,则只需将该字母写入磁带即可。
  • 如果读取的字符是数字,则整个当前磁带将重复写入数字 – 总共 1 次。

现在,如果给定某个编码字符串 S 和索引 K,则在解码后的字符串中找到并返回第 K 个字母(从 1 开始索引)。

因此,如果字符串是 “hello2World3” 且 k = 10,则输出将为 “o”。这是因为解码后的字符串将是"hellohelloWorldhellohelloWorldhellohelloWorld",因此第 10 个字符是"o"。

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

  • size := 0
  • for i in string s
    • 如果 i 是数字字符,则 size := size * i 的整数,否则 size := size + 1
  • for i in range length of s – 1 向下到 0
    • k := k mod size
    • 如果 s[i] 是数字且 k = 0,则返回 s[i]
    • 如果 s[i] 是数字,则将 size 减少 1,否则 size := size / s[i] 的整数
  • 返回空字符串

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

示例

class Solution(object):
   def decodeAtIndex(self, s, k):
      """
      :type S: str
      :type K: int
      :rtype: str
      """
      size = 0
      for i in s:
         if i.isdigit():
            size *= int(i)
         else:
            size += 1
      #print(size)
      for i in range(len(s) - 1, -1, -1):
         k %= size
         if s[i].isalpha() and k == 0:
            return s[i]
         if s[i].isalpha():
            size -=1
         else:
            size /= int(s[i])
      return ""
ob = Solution()
print(ob.decodeAtIndex("hello2World3", 10))

输入

"hello2World3"
10
ob.decodeAtIndex("hello2World3", 10)

输出

o

相关文章