In communication & networking area, we use preamble instead of delimiter.


  • 0

    I create the preamble as length of each string, and separate these lengths using '/'. And then after processing all these strings, I use '*' to separate the preamble and payload.

    class Codec:
    
        def encode(self, strs):
            preamble = ''
            for s in strs:
                preamble += ('/' if preamble else '') + str(len(s)) 
            preamble += '*'
            return preamble + ''.join(strs)
    
        def decode(self, s):
            if s == '*':
                return []
            delimiter_idx = s.find('*')
            preamble = s[:delimiter_idx]
            strs = s[delimiter_idx+1:]
            lens = map(int, preamble.split('/'))
            decode = []
            j = 0
            for i in lens:
                decode.append(strs[j:i+j])
                j += i
            return decode
    

Log in to reply
 

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