# 271\. Encode and Decode Strings
## Method 1
input = ["hello", "world!"]
output = 5 $ hello 6 $ world!
From "0th" to "just before $", is the number of chars.
So we can know number of chars after $ as one segment and the next starting point.
Then, the problem repeats itself.
## Method 2
If we know max length of a segment, we can fix number of chars to represent the segment length.
input = ["hello", "world!"]
output = 005 hello 006 world!
The first three char is for length, not segment itself.
Skip 3 chars for number and then skip 5 chars for segment. We now have 006world!. Now the problem repeats itself.
## Method 3
https://leetcode.com/problems/encode-and-decode-strings/discuss/70402/Java-with-%22escaping%22
```python
{"abc", "def"} => "abc # def # "
{'abc', '#def'} => "abc # ##def # "
{'abc##', 'def'} => "abc#### # def # "
```
```python=
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string.
"""
return ''.join([str(len(s)) + "$" + s for s in strs])
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings.
"""
result = []
start_of_count = 0
while start_of_count < len(s):
length_of_count = 1
while (start_of_count + length_of_count < len(s) and
s[start_of_count + length_of_count] != "$"):
length_of_count += 1
poisiton_of_dollar = start_of_count + length_of_count
count = int(s[start_of_count:poisiton_of_dollar])
start_of_text = poisiton_of_dollar + 1
text = s[start_of_text:start_of_text + count]
result.append(text)
start_of_count = start_of_text + count
return result
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(strs))
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string.
"""
return ''.join([str(len(s)).zfill(3) + s for s in strs])
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings.
"""
result = []
start_of_segment= 0
while start_of_segment < len(s):
number = int(s[start_of_segment:start_of_segment + 3])
next_start_of_segment = start_of_segment + 3 + number
text = s[start_of_segment + 3: next_start_of_segment]
result.append(text)
start_of_segment = next_start_of_segment
return result
"""
https://leetcode.com/problems/encode-and-decode-strings/discuss/70402/Java-with-%22escaping%22
"""
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string.
"""
for i, s in enumerate(strs):
strs[i] = s.replace("#", "##")
return '_#_'.join(strs)
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings.
"""
result = s.split("_#_")
for i, x in enumerate(result):
result[i] = x.replace("##", "#", -1)
return result
```