Python索引处的解码字符串
假设给出一个编码字符串S。我们必须找到解码后的字符串并将其写入磁带,这里一次读取一个字符的编码后的字符串,然后执行以下步骤:
如果读取的字符是字母,则只需将该字母写到磁带上。
如果读取的字符是数字,则将整个当前磁带重复写入数字-总共再写入1次。
现在,如果给出了一些编码后的字符串S并给出了索引K,则在解码后的字符串中找到并返回第K个字母(从1开始的索引)。
因此,如果字符串为“hello2World3”且k=10,则输出将为“o”。这是因为解码后的字符串将为“hellohelloWorldhellohelloWorldhellohelloWorld”,因此第十个字符为“o”。
为了解决这个问题,我们将遵循以下步骤-
大小:=0
为我在字符串s
如果i是数字字符,则size:=size*i的整数,否则size:=size+1
对于i,其范围为s–1到0
k:=kmod大小
如果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