Python中索引处的解码字符串
假设给定一个编码字符串S。我们必须找到并将解码后的字符串写入磁带,这里编码字符串一次读取一个字符,并执行以下步骤:
- 如果读取的字符是字母,则该字母直接写入磁带。
- 如果读取的字符是数字,则整个当前磁带将重复写入数字-1次。
现在,如果给定某个编码字符串 S 和索引 K,则查找并返回解码字符串中的第 K 个字母(从 1 开始索引)。
因此,如果字符串是“hello2World3”,k = 10,则输出将是“o”。这是因为解码后的字符串将是“hellohelloWorldhellohelloWorldhellohelloWorld”,所以第 10 个字符是“o”。
为了解决这个问题,我们将遵循以下步骤:
- size := 0
- 对于字符串s中的每个i
- 如果i是数字字符,则size := size * i的整数值,否则size := size + 1
- 对于s长度-1到0的范围内的i
- 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP