Encode and Decode String

题目描述

解题方法

Solution

class Codec:

    def encode(self, strs):
        """Encodes a list of strings to a single string.

        :type strs: List[str]
        :rtype: str
        """
        result = ""
        for s in strs:
            result += str(len(s)) + "#" + s
        return result

    def decode(self, s):
        """Decodes a single string to a list of strings.

        :type s: str
        :rtype: List[str]
        """
        strs = []
        i = 0
        while i < len(s):
            j = s.find("#", i) # 找到#的位置
            l = int(s[i:j])
            cur_s = s[j+1:j+1+l]
            strs.append(cur_s)
            i = j + 1 + l
        return strs

Reference