Skip to content
LC-0271 Medium LeetCode Premium

271. Encode and Decode Strings

This is a LeetCode premium problem — the official page requires a subscription. Read the full statement on leetcode.ca, a community mirror.
Difficulty: medium Acceptance: 49% Topics: Array, String, Design
View full problem on leetcode.ca
Official page on LeetCode (premium)

The link at the top of the mirror page opens the solution — skip it if you want to solve this yourself.

leetcode.ca is an independent community site — we don't own or maintain it, and it isn't affiliated with LeetCode.

Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(1)

class Codec(object):

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

        :type strs: List[str]
        :rtype: str
        """
        encoded_str = ""
        for s in strs:
            encoded_str += "%0*x" % (8, len(s)) + s
        return encoded_str


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

        :type s: str
        :rtype: List[str]
        """
        i = 0
        strs = []
        while i < len(s):
            l = int(s[i:i+8], 16)
            strs.append(s[i+8:i+8+l])
            i += 8+l
        return strs

Solution from kamyu104/LeetCode-Solutions · MIT