20140: 今日化学论文
http://cs101.openjudge.cn/practice/20140/
常凯申同学发现自己今日化学论文字数抄上限了,决定采取如下的压缩方法萌混过关:
把连续的x个字符串s记为[xs]。(1 <= x <= 100)
但这样的方法当然骗不过lwh老师啦。老师非常生气,但出于好奇,还是想看一看常凯申同学写了什么。 请你帮老师还原出原始的论文。
输入
仅一行,由小写英文字母、数字和[]组成的字符串(其中不含空格)
输出
一行,原始的字符串。
样例输入
[2b[3a]c]样例输出
baaacbaaac来源: cs101-2019 柏敬尧v0.2
python
s = input()
stack = []
for i in range(len(s)):
stack.append(s[i])
if stack[-1] == "]":
stack.pop()
helpstack = []
while stack[-1] != "[":
helpstack.append(stack.pop())
stack.pop()
numstr = ""
while helpstack[-1] in "0123456789":
numstr += str(helpstack.pop())
helpstack = helpstack*int(numstr)
while helpstack != []:
stack.append(helpstack.pop())
print(*stack, sep="")本地调试可以用sys.stderr.write(checkpoint)。如果精神不集中写程序太难受了,调试的print忘记注释造成WA,会耽误很久。
递归实现,避免使用全局变量。
python
import sys
def recursive_decode(s, idx):
stack = []
numstr = ""
while idx < len(s):
sys.stderr.write(s)
sys.stderr.write(s[idx])
if s[idx] == "[":
decoded_str, next_idx = recursive_decode(s, idx + 1)
stack.extend(decoded_str)
idx = next_idx
elif s[idx] == "]":
num = int(numstr)
return stack * num, idx
elif s[idx].isdigit():
numstr += s[idx]
else:
stack.append(s[idx])
idx += 1
return stack, idx
s = input()
#s = "[2b[3a]c]"
decoded_str, _ = recursive_decode(s, 0)
print(*decoded_str, sep="")