From 3e7d66d2d68e0818883d6e44fe4091d2fe3dc360 Mon Sep 17 00:00:00 2001 From: ImAlpha Date: Wed, 6 Sep 2023 09:15:07 -0700 Subject: [PATCH] Solution Using length of string to encode and decode --- .../Encode_Decode_Strings.py | 14 ---------- .../Two_Pointers/Encode_Decode_Strings.py | 26 +++++++++++++++++++ 2 files changed, 26 insertions(+), 14 deletions(-) delete mode 100644 NeetCodeRoadmap/Arrays_and_Hashing/Encode_Decode_Strings.py create mode 100644 NeetCodeRoadmap/Two_Pointers/Encode_Decode_Strings.py diff --git a/NeetCodeRoadmap/Arrays_and_Hashing/Encode_Decode_Strings.py b/NeetCodeRoadmap/Arrays_and_Hashing/Encode_Decode_Strings.py deleted file mode 100644 index bfd72da..0000000 --- a/NeetCodeRoadmap/Arrays_and_Hashing/Encode_Decode_Strings.py +++ /dev/null @@ -1,14 +0,0 @@ -def encode(strs): - # write your code here - key = [] - encode = [] - for x in strs: - if x in key: - encode.append(x) - -""" -@param: str: A string -@return: decodes a single string to a list of strings -""" -def decode(str): - # write your code here \ No newline at end of file diff --git a/NeetCodeRoadmap/Two_Pointers/Encode_Decode_Strings.py b/NeetCodeRoadmap/Two_Pointers/Encode_Decode_Strings.py new file mode 100644 index 0000000..c491ca1 --- /dev/null +++ b/NeetCodeRoadmap/Two_Pointers/Encode_Decode_Strings.py @@ -0,0 +1,26 @@ +def encode(strs): + # write your code here + res = '' + for s in strs: + encoded = str(len(s)) + '/' + s + res += encoded + return res +""" +@param: str: A string +@return: decodes a single string to a list of strings +""" +def decode(str): + # write your code here + res, i = [], 0 + while i < len(str): + # For example, 12/abc + e = i + while e < len(str) and str[e] != '/': + e += 1 + size = int(str[i:e]) + word = str[e + 1, e + 1 + size] + i = e + 1 + size + res.append(word) + return res + +print(encode(["lint", "code", "love", "you"])) \ No newline at end of file