zoukankan      html  css  js  c++  java
  • Python 解LeetCode:394 Decode String

    • 题目描述:按照规定,把字符串解码,具体示例见题目链接

    • 思路:使用两个栈分别存储数字和字母

    • 注意1: 数字是多位的话,要处理后入数字栈

    • 注意2: 出栈时过程中产生的组合后的字符串要继续入字母栈

    • 注意3: 记得字母出栈的时候字符要逆序组合成字符串

    • 注意4: 不用字符串而用字母栈的原因是字符串的 join 效率会比字符串加法高一些

    • 结果: 30 ms, beat 98.02%

    • 缺点:判断是数字那里有点代码不简洁,可以把 j 挪到循环外面的

    class Solution(object):
        def decodeString(self, s):
            """
            :type s: str
            :rtype: str
            """
            nums, chars = [], []
            i, length = 0, len(s)
            while i < length:
                j = i + 1
                if s[i].isdigit():
                    num = int(s[i])
                    while j < length:
                        if s[j].isdigit():
                            num = num * 10 + int(s[j])
                            j += 1
                        else:
                            break
                    nums.append(num)
                elif s[i] == '[' or s[i].isalpha():
                    chars.append(s[i])
                else:
                    t, tmpc = chars.pop(), []
                    while t != '[':
                        tmpc.append(t)
                        t = chars.pop()
                    tchars = nums.pop() * ''.join(tmpc[::-1])
                    chars.append(tchars)
                i = j
            return ''.join(chars)
    
  • 相关阅读:
    用遗传算法解决子集和问题
    XML映射配置文件
    generator插件配置方式使用
    声明
    spring IOC简单分析
    模板模式
    原型模式
    委派模式,策略模式
    单例模式2
    单例模式
  • 原文地址:https://www.cnblogs.com/qiaojushuang/p/9048675.html
Copyright © 2011-2022 走看看