字符串解压缩问题——贪心算法

 

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()

  

转载于:https://www.cnblogs.com/bonelee/p/11580584.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值