本周Leetcode问题-06.28

做题真是做得很开心,特别是做着做着就半夜了的时候,本周按照Leetcode上的前几届contest找题,在下面给出两道:

394Decode 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"

emmmm,我理解这是一道很典型的使用栈结构的题,有这么几个东西需要处理,首先比如读入数字100,需要把1,0,0转换为一整个数字,其次读入字符时,我把它合并成了字符串,然后碰到右括号时进行处理,此时栈大概是这样子的:

                  ‘一个数字    [    一个字符串’

处理成一个新的字符串并压入。

        if (len(s)==0):
            return ''
        result=''
        stacklength=len(s)
        stack=['']*stacklength
        index=0
        tmpstr=''
        num=0
        for i in s:
            if (i.isdigit()):       压入数字
                stack[index]=i
                if (index!=0 and stack[index-1].isdigit()):
                    stack[index-1]=stack[index-1]+stack[index]    将1,0,0这种的处理成100
                elif (index!=0 and stack[index-1]!='['):   
                    index+=1
                else:                   这里处理得不是很好,在每个数字前面如果没有字符串加了一个空字符‘’
                    stack[index+1]=i
                    stack[index]=''
                    index+=2
            elif (i=='['):           碰到 [ 直接读入就行了
                stack[index]=i
                index+=1
            elif (i!=']'):       碰到字符一个一个将其拼接为字符串
                stack[index]=i
                if (index!=0 and stack[index-1]!='['):
                    stack[index-1]=stack[index-1]+stack[index]
                else:
                    index+=1
            else:    然后找到num[string]这种格式,返回stringstringstring......的字符串
                num=int(stack[index-3])  就是这里处理有点问题,数字在2[b2[a]]与2[2[a]]的位置有点不一样
                tmpstr=stack[index-1]
                stack[index-4]+=num*tmpstr
                index-=3

        return stack[0]

Leetcode有意思的一点是你兴高采烈通过了例子的代码未必能最终过,因为他准备一堆刁钻的输入来测试你,所以啊,碰到列表记得空列表,碰到整数记得零以及负数,还有大数据量样本,考量你的算法复杂度,当然了,就在一次次错误中学习吧!

猜你喜欢

转载自blog.csdn.net/weixin_42405231/article/details/80850037