File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ # 271. Encode and Decode Strings
3+
4+ ## Time and Space Complexity
5+
6+ Use ":" as a separator and also store the length of each string to decode the string correctly.
7+
8+
9+ ### encode
10+
11+ ```
12+ TC: O(n * k)
13+ SC: O(m)
14+ ```
15+
16+ #### TC is O(n * k):
17+
18+ - iterating through the list of strings and appending each string to the result. = O(n * k)
19+ - f-string is O(k)
20+
21+ #### SC is O(m):
22+ - storing the result in a string.
23+
24+ ### decode
25+
26+ ```
27+ TC: O(m)
28+ SC: O(m)
29+ ```
30+
31+ #### TC is O(m):
32+ - iterating over the string until the string length is 0. = O(m)
33+ - do list slicings for extract parts and removing the processed section = each operation takes O(k)
34+
35+ #### SC is O(m):
36+ - storing the result in a list(total length of strings is m) = O(m)
37+
38+ '''
39+
40+ class Solution :
41+ """
42+ @param: strs: a list of strings
43+ @return: encodes a list of strings to a single string.
44+ """
45+ def encode (self , strs ):
46+ result = ''
47+ for str in strs : # TC: O(n)
48+ result += f"{ len (str )} :{ str } " # TC: O(k)
49+ return result
50+
51+ """
52+ @param: str: A string
53+ @return: decodes a single string to a list of strings
54+ """
55+ def decode (self , str ):
56+ result = []
57+
58+ while len (str ) > 0 : # TC: O(m)
59+ length = int (str [:1 ]) # TC: O(k)
60+ string = str [2 :length + 2 ] # TC: O(k)
61+ str = str [length + 2 :] # TC: O(k)
62+
63+ result .append (string ) # SC: O(m)
64+
65+ return result
You can’t perform that action at this time.
0 commit comments