Tôi chỉ tìm ra một câu trả lời:
các cơ sở là:
1. the expression has been tokenized
2. no syntax error
3. there are only binary operators
đầu vào:
list of the tokens, for example:
(, (, a, *, b,), +, c,)
đầu ra:
set of the redundant parentheses pairs (the orders of the pairs are not important),
for example,
0, 8
1, 5
hãy nhận thức được rằng: tập không phải là độc đáo, ví dụ, ((a + b)) * c, chúng tôi có thể xóa dấu ngoặc đơn bên ngoài hoặc dấu bên trong, nhưng biểu thức cuối cùng là duy nhất
cấu trúc dữ liệu:
a stack, each item records information in each parenthese pair
the struct is:
left_pa: records the position of the left parenthese
min_op: records the operator in the parentheses with minimum priority
left_op: records current operator
thuật toán
1.push one empty item in the stack
2.scan the token list
2.1 if the token is operand, ignore
2.2 if the token is operator, records the operator in the left_op,
if min_op is nil, set the min_op = this operator, if the min_op
is not nil, compare the min_op with this operator, set min_op as
one of the two operators with less priority
2.3 if the token is left parenthese, push one item in the stack,
with left_pa = position of the parenthese
2.4 if the token is right parenthese,
2.4.1 we have the pair of the parentheses(left_pa and the
right parenthese)
2.4.2 pop the item
2.4.3 pre-read next token, if it is an operator, set it
as right operator
2.4.4 compare min_op of the item with left_op and right operator
(if any of them exists), we can easily get to know if the pair
of the parentheses is redundant, and output it(if the min_op
< any of left_op and right operator, the parentheses are necessary,
if min_op = left_op, the parentheses are necessary, otherwise
redundant)
2.4.5 if there is no left_op and no right operator(which also means
min_op = nil) and the stack is not empty, set the min_op of top
item as the min_op of the popped-up item
ví dụ
dụ một
((a*b)+c)
sau khi quét để b, chúng tôi đã ngăn xếp:
index left_pa min_op left_op
0
1 0
2 1 * * <-stack top
bây giờ chúng tôi gặp đầu tiên ')' (tại pos 5), chúng tôi bật mục
left_pa = 1
min_op = *
left_op = *
và tiền đọc điều hành '+', vì ưu tiên min_op '*'> '+', vì vậy các cặp (1,5) là dư thừa, do đó, đầu ra nó. sau đó quét đến chúng ta gặp nhau cuối cùng ')', vào lúc này, chúng tôi đã ngăn xếp
index left_pa min_op left_op
0
1 0 + +
chúng tôi bật mục này (kể từ khi chúng ta gặp nhau ')' tại pos 8), và tiền đọc điều hành tiếp theo, kể từ khi có không điều hành và ở chỉ số 0, không có left_op, vì vậy sản lượng cặp (0, 8)
dụ hai
a*(b+c)
khi chúng ta gặp những ')', chồng cũng giống như:
index left_pa min_op left_op
0 * *
1 2 + +
bây giờ, chúng tôi bật mục ở chỉ mục = 1, so sánh min_op '+' với left_op '*' ở chỉ mục 0, chúng tôi có thể tìm ra '(', ')' là cần thiết
Các giải pháp khác sẽ được phân tích sự biểu hiện thành một cây biểu hiện, như ở đây: http://stackoverflow.com/questions/9136153/build-binary-expression-tree – BartoszKP