From 676bc6e96eb4cdae7fe666122495b2089a40ebea Mon Sep 17 00:00:00 2001 From: ivan Date: Sat, 11 Jul 2026 05:21:57 -0600 Subject: [PATCH] adding updates --- .../round_1/15_encode_and_decode_strings.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/my_project/interviews/google_top_exercises/round_1/15_encode_and_decode_strings.py diff --git a/src/my_project/interviews/google_top_exercises/round_1/15_encode_and_decode_strings.py b/src/my_project/interviews/google_top_exercises/round_1/15_encode_and_decode_strings.py new file mode 100644 index 00000000..a5c46c2b --- /dev/null +++ b/src/my_project/interviews/google_top_exercises/round_1/15_encode_and_decode_strings.py @@ -0,0 +1,30 @@ +from typing import List + + + +class Codec: + def encode(self, strs: List[str]) -> str: + """Encodes a list of strings to a single string. + + Length-prefix each string as "#". The delimiter '#' + is unambiguous because we always know the exact number of chars + to read from the length that precedes it, so any character + (including '#') may appear inside a string. + """ + return "".join(f"{len(s)}#{s}" for s in strs) + + def decode(self, s: str) -> List[str]: + """Decodes a single string to a list of strings. + """ + strs = [] + i = 0 + n = len(s) + while i < n: + # Read the length up to the '#' delimiter. + j = s.index("#", i) + length = int(s[i:j]) + # The string is the next `length` chars after the '#'. + start = j + 1 + strs.append(s[start:start + length]) + i = start + length + return strs \ No newline at end of file