Encode and Decode Strings

这题的编码方式实在太多太自由,这里先写了一种九章课上略提起没有解释的最普通算法,即将字符串长度加上一个冒号加到字符串本身上进行编码再解码,需要注意的是,我们必须在大循环中一次处理一整个字符而不能只完成部分工作,下面是代码

class Codec:

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

        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''
        result = ''
        for string in strs:
            result += `len(string)` + ':' + string
        return result

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

        :type s: str
        :rtype: List[str]
        """
        if not s:
            return []

        result = []
        n = len(s)
        cur = 0
        count = 0
        while cur < n:
            while cur < n and s[cur].isdigit():
                count = 10 * count + ord(s[cur]) - ord('0')
                cur += 1
            cur += 1

            tmp = ''
            while cur < n and count > 0:
                tmp += s[cur]
                cur += 1
                count -= 1

            result.append(tmp)

        return result

results matching ""

    No results matching ""