zoukankan      html  css  js  c++  java
  • 字符串解压缩问题——贪心算法

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

      

  • 相关阅读:
    python爬虫
    RMQ算法
    组合数
    水池数目
    jQuery 拼接事件
    ORACLE
    day 75
    day74 vue框架
    day73 vue框架
    day 72 vue框架
  • 原文地址:https://www.cnblogs.com/bonelee/p/11580584.html
Copyright © 2011-2022 走看看