一,问题描述
1, 给定一个字符串,目标是将写在#
和%
之间的字符串,重复#号前面的数字次数(数字只会是个位数),
2,例如: 输入结果: strs = "he3#llo%world
"
输出结果: res = "hellollolloworld"
输入结果:strs = "he3#ll2#o%wo%rld"
输出结果: res = "helloowolloowollooworld"
3, 算法思想: 利用一个栈数据结构,用来存放"#"对应的索引下标,在遍历字符串中,若遇到"%",则将栈中的元素退出来,进行匹配操作。
二, 程序:
1, 程序
class Solution(object):
def __init__(self):
# 主要存放"#"字符对应的下标
self.stack = []
def makestrs(self, strs):
if strs == "" or len(strs) == 0:
return strs
data = 0
i = 0
# 遍历字符串
while i < len(strs):
# 碰到"#"字符,就将索引值存入stack中
if strs[i] == "#" and i != 0:
self.stack.append(i)
# 碰到"%"字符, 就从stack中推出元素
elif strs[i] == "%" and i != 0:
left = self.stack.pop()
right = i
if left != 0:
if strs[left -1].isdigit():
data = int(strs[left-1])
temp = data * strs[left+1:right]
strs = strs[0:left-1] + temp + strs[right+1:]
i = len(strs[0:left-1] + temp)
i = i + 1
if len(self.stack) > 0:
return None
else:
return strs
if __name__ == "__main__":
solution = Solution()
# strs = "he3#llo%world"
strs = "he3#ll2#o%wo%rld"
res = solution.makestrs(strs)
print("res = %s" % res)