LeetCode 394. Decode String

231 篇文章 0 订阅

Given an encoded string, return its 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".

---------------------------------------------------------------------------------------

这道题目非常好,很容易想到用栈来表示这种树状的关系。但问题是不光有嵌套的问题,还有并列的问题,两个examples都给的非常好。直观上感觉需要两个栈,但是codes很容易写成下面这样:

class Solution:
    def fetch_num(self,s,start):
        i,l=start,len(s)
        while (i<l and s[i]>="0" and s[i]<="9"):
            i+=1
        return i
    def fetch_str(self,s,start):
        i,l=start,len(s)
        while (i<l and s[i]>="a" and s[i]<="z"):
            i+=1
        return i
    def decodeString(self, s):
        nums,strs = [],[]
        l,i = len(s),0

        while (i<l):
            if (s[i]>="0" and s[i]<='9'):
                j = self.fetch_num(s,i)
                nums.append(int(s[i:j]))
                i = j
            elif (s[i] == '['):
                i += 1
            elif (s[i] == ']'):
                num,cur=nums.pop(),strs.pop()
                strs.append(num*cur)
                i += 1
            else:
                j = self.fetch_str(s,i)
                strs.append(s[i:j])
                i = j
        print(nums)
        print(strs)
        return ''.join(strs)

s = Solution()
print(s.decodeString(s = "3[a2[c]]"))

写成这样的根本问题是没有表示出数字和字符串的映射关系。因此,从栈的设计角度就把两个栈合成一个栈两个字段的映射关系,得到的codes如下:

class Solution:
    def decodeString(self, s):
        sta,numstr = [[0,'']],'' #bug1: sta=[]
        for ch in s:
            if (ch >= "0" and ch <= "9"):
                numstr += ch
            elif (ch == '['):
                sta.append([int(numstr),''])
                numstr = ''
            elif (ch == ']'):
                num,cur = sta.pop()
                sta[-1][1] += num*cur
            else:
                sta[-1][1] += ch
        return sta[-1][1]
s = Solution()
print(s.decodeString("2[abc]3[cd]ef"))

当然这种题目还可以递归,当然递归的前提也是既要考虑并列也要考虑嵌套,转一个discussion的codes:

class Solution:
    def decodeString(self, s):
        sta,numstr = [[0,'']],'' #bug1: sta=[]
        for ch in s:
            if (ch >= "0" and ch <= "9"):
                numstr += ch
            elif (ch == '['):
                sta.append([int(numstr),''])
                numstr = ''
            elif (ch == ']'):
                num,cur = sta.pop()
                sta[-1][1] += num*cur
            else:
                sta[-1][1] += ch
        return sta[-1][1]
s = Solution()
print(s.decodeString("2[abc]3[cd]ef"))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值