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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM