【发布时间】:2020-08-20 13:48:34
【问题描述】:
我正在尝试使用基于堆栈的方法来解析编码字符串。 此链接描述了编码:https://www.bittorrent.org/beps/bep_0003.html
我的伪代码无法处理存在嵌套列表的情况,例如 [1, [2]] 和 [[1, 2]] 都将返回 [[1 ,2]],即使显然编码不同,"li1eli2eee" 与 "lli1ei2eee"。
到目前为止,这是我的伪代码
input: string
output: map/list/integer/string in a bencoded data structure
first, tokenize the string into valid tokens
Valid tokens "d, l, [words], [numbers], e, s (virtual token)"
Strings are tokenized as 4:spam becomes "s spam e" with s being a virtual token
Eg. li1el4:spamee becomes [l i 1 e i 22 e l s spam e i 2 e e e]
Parsing:
make two stacks:
stack1
stack2
for token in tokens:
if stack is empty
return error
if the token isn’t an “e”
push token onto stack1
while the stack isn’t empty:
elem = pop off the stack
if elem is “i”
elem2 = pop elem off stack2 and check if it can be converted to an int
if not
return error
push elem2 onto stack2 again
elif elem is “d”
make a new dict
while stack2 isn’t empty:
key = pop off stack2
if stack2 is empty:
return error (because then we have an odd key value encoding)
value = pop off stack2
dict[key] = value
push dict onto stack2
elif elem is “l”
make a new list
while stack2 isn’t empty:
append pop off stack2 to l
push l onto stack2
elif elem is “s”
dont need to do anything :P
else
push elem onto stack2
if stack2 isn’t empty:
ret = pop the lone element off stack2
if stack2 isn’t empty:
return error
return ret
【问题讨论】:
-
“Bencoding”的规范对我来说不是很清楚,即使查看了链接和其他几个地方,如npm package。此代码似乎没有考虑字典可能嵌套的可能性。那不可能吗?至于列表和字典,
while stack2 isn't empty循环似乎总是错误的。如果您有一个实现,那么共享比伪代码更有意义。感谢您的澄清。 -
字典可以嵌套,列表也可以嵌套。 stack2 不为空的想法是将所有内容包含在列表或字典中。本质上,stack2 被用作列表或字典数据结构的临时存储。
-
好的,谢谢。我的回答符合你的要求吗?如果没有,请随时告诉我我错过了什么,我会更新。
标签: algorithm parsing recursion stack tokenize