KK's blog

每天积累多一些

0%

KV Store Serialize & Deserialize


Implement a key-value store that can serialize multiple string key-value pairs into a single string and deserialize it back. Both keys and values can contain any characters including delimiters, newlines, and special characters.

Example 1:

Input: {“a,”: “4,,5”, “b”: “”}


题目大意:

实现一个serialize和deserialize键值存储的方法。

解题思路:

用key和value的长度及自定义分隔符[][]来作为serialized的一部分,从而避开delimiter的限制.
上面的例子serialize后变成[2]a,[4]4,,5[1]b[0]

解题步骤:

N/A

注意事项:

  1. 不用+=连接res,用list和join提交效率
  2. 用index方法找自定义分隔符而不是逐字符处理
  3. 重复代码来处理token可以放入子函数,用nonlocal不用作为输入参数且可以修改此变量

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def serialize(kv):
tokens = []
for k, v in kv.items():
tokens.append(f"[{len(k)}]{k}[{len(v)}]{v}")
return "".join(tokens)

def deserialize(serialized):
i = 0
dict = {}
while i < len(serialized):

def get_token(s):
nonlocal i
token_len_st = serialized.find("[", i) + 1
token_len_end = serialized.find("]", i)
token_len = int(serialized[token_len_st:token_len_end])
token_st = token_len_end + 1
i = token_st + token_len
return serialized[token_st:token_st + token_len]

k = get_token(serialized)
v = get_token(serialized)
dict[k] = v
return dict

算法分析:

时间复杂度为O(n),空间复杂度O(n)

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def serialize2(kv):
res = ""
for k, v in kv.items():
res += f"[{len(k)}]{k}[{len(v)}]{v}"
return res

def deserialize2(serialized):
is_key = True
i, kv_length = 0, -1
k, v = "", ""
dict = {}
serialized += " "
while i < len(serialized):
if kv_length >= 0:
if is_key:
k = serialized[i:i + kv_length] # a,
else:
v = serialized[i:i + kv_length] # 4,,5
dict[k] = v
is_key = False if is_key else True
i += kv_length
kv_length = -1
if serialized[i] == "[":
st = i + 1 # 6
elif serialized[i] == "]":
end = i # 2
kv_length = int(serialized[st:end]) # 4
i += 1
return dict
Free mock interview