Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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".

My code:

class Solution(object):
    def decodeString(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s)<=1:
            return s
        combine_str=""
        i=0
        while i<len(s):
            if ord(s[i])>=49 and ord(s[i])<=57:
                k=i+1
                while ord(s[k])>=48 and ord(s[k])<=57:
                    k=k+1
                number=int(s[i:k])
                i=k
                count=0
                while k<len(s):
                    if s[k]=='[':
                        count+=1
                    if s[k]==']':
                        count-=1
                    if count==0:
                        break
                    k=k+1
                new_str=self.decodeString(s[i+1:k])
                combine_str=combine_str+new_str*number
                i=k+1
            else:
                combine_str=combine_str+s[i]
                i+=1
        return combine_str
        

Solution: https://leetcode.com/problems/decode-string/