Not a proper way to AC

  • 0

    This piece of code can be got AC, the basic idea is to join all the string with some very special pattern, it's not proper because it will become crashed when the pattern actually appears on the string itself. I believe a more reasonable way is to join all the string and append with a suffix array with individual entry is exactly a say 8-bits number string where s[-1] denote how much more fixed length of arrays are ahead of it, and then backtracking those length, and then will be relatively safe to decode.

    class Codec:
        def encode(self, strs):
            if not strs:
                return "None"
            return '|--|'.join(strs)
        def decode(self, s):
            if s == "None":
                return []
            return s.split('|--|')

    A more decent way to AC:

    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
            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:
                    s = s[counter[i]:]
            return ans

Log in to reply

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