Using '\t as delimiter instead of using length of each string


  • -3
    T

    I think the most important point is to use two chars as delimiter, for example, "\t".
    and for the first character in your delimiter, like '' in "\t", you have to replace '' by "\\".
    so that you won't be confused when decoding.

    Another thing to note is that because '' is escape character in python. len('\t) equals one;
    and you have to use "\\" to represent "'; and when you print('\\")
    it will give you "\".

    But the fundamental idea remain unchanged.

    class Codec:
        
            def encode(self, strs):
                """Encodes a list of strings to a single string.
                
                :type strs: List[str]
                :rtype: str
                """
                return ''.join([s.replace('\\','\\\\') + '\t'for s in strs])
        
            def decode(self, s):
                """Decodes a single string to a list of strings.
                
                :type s: str
                :rtype: List[str]
                """
                s=s.replace('\\\\','\\')
                return s.split('\t')[:-1]

  • 0

    Doesn't work:

    >>> codec = Codec()
    >>> strs = ['a\tb']
    >>> strs
    ['a\tb']
    >>> codec.decode(codec.encode(strs))
    ['a', 'b']
    

Log in to reply
 

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