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

      

  • 相关阅读:
    内存溢出和内存泄漏的区别
    测试管理三要素(人员、过程和技术)
    面试可提问的6个问题
    弱网测试(二)
    js捕获错误
    TortoiseGit自动记住用户名密码的方法
    win7 "com surrogate“ 已停止工作的解决办法
    仿百度图片毛玻璃效果
    毛玻璃效果
    vimium快捷键列表
  • 原文地址:https://www.cnblogs.com/bonelee/p/11580584.html
Copyright © 2011-2022 走看看