Leetcode-394題:Decode String

Given an encoded string, return it's decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

代碼:

class Solution(object):
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        stack = []
        i = 0
        while i < len(s):
            if s[i] == ']':
                ll = []
                t = stack.pop()
                while True:
                    if t.isdigit():
                        stack.append(''.join(ll * int(t)))
                        break
                    elif t == '[':
                        pass
                    else:
                        ll.insert(0, t)
                    t = stack.pop()
            elif s[i].isdigit():
                ll = []
                while s[i].isdigit():
                    ll.append(s[i])
                    i += 1
                stack.append(''.join(ll))
                continue
            else:
                stack.append(s[i])
            i += 1
        return ''.join(stack)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評(píng)論 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    網(wǎng)事_79a3閱讀 12,979評(píng)論 3 20
  • 007很流行的一句話 截止日期是第一生產(chǎn)力 我覺(jué)得說(shuō)的特別貼切。 生產(chǎn)力,百度百科的解釋是,人類創(chuàng)造新財(cái)富的能力。...
    飄飄輕閱讀 6,748評(píng)論 0 8
  • 曾經(jīng)自己是個(gè)做事沒(méi)有計(jì)劃,效率的人。總是因?yàn)楦鞣N緊急且重要的事,因?yàn)闆](méi)有養(yǎng)成良好的習(xí)慣,沒(méi)有在事情重要且不緊...
    華珍卓越覺(jué)醒閱讀 413評(píng)論 2 1
  • 時(shí)間把海水熬成了沉悶的風(fēng)暴。 一觸即發(fā)的如同兵臨城下的戰(zhàn)爭(zhēng)。 你渴求的無(wú)風(fēng)無(wú)浪的寧?kù)o早晨也許只是憑記憶勾勒的畫(huà)。 ...
    呂旅閱讀 289評(píng)論 0 0

友情鏈接更多精彩內(nèi)容