add extra information at the end of the string for the purpose to decode


  • 0
    def getFiveDigitNum(self, l):
        while len(l) < 5:
            l = '0' + l
        return l
    
    def encode(self, strs):
        """Encodes a list of strings to a single string.
    
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''
        l = self.getFiveDigitNum(str(len(strs)))
    
        ans = []
        decode = ''
        for s in strs:
            decode += s
            ans.append(self.getFiveDigitNum(str(len(s))))
        ans.append(l)
        decode += ''.join(ans)
        return decode
    
    def decode(self, s):
        """Decodes a single string to a list of strings.
    
        :type s: str
        :rtype: List[str]
        """
        if not s:
            return []
        length = int(s[-5:])
        counter = []
        for i in xrange(2, length+2):
            counter.append(int(s[-i * 5 :-(i - 1) * 5]))
        ans = []
        for i in xrange(len(counter)-1, -1, -1):
            if counter[i] != 0:
                ans.append(s[:counter[i]])
                s = s[counter[i]:]
            else:
                ans.append('')
        return ans

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.