# 271. Encode and Decode Strings

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

I have a very simple outlook on this question- let the strings be \["something", "that", "is", "the", "string"\].

During transmission after encoding, the string will be "somethingthatisthestring" lets say.

We just have to keep track of the end of every word here. We could use something like index tracking, even the idea of **"something that is the string"** does not look bad to me because the decoder can just check for spaces and separate words.

But even more concrete way is to record the length of each string and later search for the indices in the decoder.

```plaintext
class Solution:

    def encode(self, strs: List[str]) -> str:
        if not strs:
            return ""
        sizes, res = [],""
        for s in strs:
            sizes.append(len(s))
        for sz in sizes:
            res += str(sz)
            res += ','
        res += '#'
        for s in strs:
            res += s
        return res

    def decode(self, s: str) -> List[str]:
        if not s:
            return ""
        sizes, res, i = [], [] ,0
        while s[i] != '#':
            cur = ""
            while s[i] != ',':
                cur += s[i]
                i += 1
            sizes.append(int(cur))
            i += 1
        i += 1
        for sz in sizes:
            res.append(s[i:i + sz])
            i += sz
        return res
```

Here, we take the given strings, note their lengths at the start of the encoded string, then we out a # in between for separation. Now, we write all the string in the given list respectively.
