import sys
def load_data():
return sys.stdin.read()
def get_position_map(s):
result = {}
stack = []
for i,c in enumerate(s):
if c == "[":
result[i] = -1
stack.append(i)
elif c == "]":
if stack:
pos = stack.pop()
result[pos] = i
return result
def decode_str(s, start, end, pos_map):
def in_range(i, start, end):
return start<=i<end
def is_str(c):
return ord('a')<=ord(c)<=ord('z') or ord('A')<=ord(c)<=ord('Z')
def is_num(c):
return ord('0') <= ord(c) <= ord('9')
result = ""
i = start
while in_range(i, start, end):
string = ""
while in_range(i, start, end) and is_str(s[i]):
string += s[i]
i += 1
if not in_range(i, start, end):
return string
digit = ""
while in_range(i, start, end) and is_num(s[i]):
digit += s[i]
i += 1
if not in_range(i, start, end):
return string
if pos_map[i] == -1:
return string
d_str = decode_str(s, i+1, pos_map[i], pos_map)
result += string + d_str*int(digit)
i = pos_map[i]+1
return result
def main():
encoded_str = load_data() # "abc3[xyz4[mn]" # "abc3[xyz" # "abc2[xyz3[mn]]" #"aaabcbc" #"3[a]2[bc]"
pos_map = get_position_map(encoded_str)
decoded_str = decode_str(encoded_str, 0, len(encoded_str), pos_map)
print(decoded_str)
if __name__ == "__main__":
main()
标签:return,解压缩,pos,start,算法,result,stack,def,贪心 From: https://blog.51cto.com/u_11908275/6384767