键盘输入一个含有括号的四则运算表达式,可能含有多余的括号,编程整理该表达式,去掉所有多余的括号,原表达式中所有变量和运算符相对位置保持不变,并保持与原表达式等价。
设待整理的表达式为(s1 op s2);op为括号内优先级最低的运算符(“+”,“-”或“*”,“/”);
左邻括号的运算符为“/”,则括号必须保留,即…/(s1 op s2)…形式。
左邻括号的预算符为“*”或“-”。而op为“+”或“-”,则保留括号,即…*(s1+s2)…或…-(s1+s2)…或…*(s1-s2)…或…-(s1-s2)…。
右邻括号的运算符为“*”或“/”,而op为“+”或“-”,原式中的op运算必须优先进行,因此括号不去除,即(s1+s2)*…
除上述情况外,可以括号去除.。
帮忙转C++ 也行
program CTSC94_1;
const
Inp = 'input.txt';
Outp = 'output.txt';
var
Ch: Char;
Expr: string;
function RightBracket(S:string;I:Byte):Byte; {在S串中找到下一个运算符的位置}
var Q: Byte; {Q用来记录括号层数}
begin
Q := 1;
repeat
Inc(I);
if S[I] = '(' then
Inc(Q)
else
if S[I] = ')' then Dec(Q);
until Q = 0;
RightBracket := I;
end;
function Find(S: string): Byte; {找到优先级别最低的运算符的位置}
var
I, K: Byte;
begin
I := 1; K:= 0;
while I <= Length(S) do begin
if (S[I] = '+') or (S[I] = '-') then begin
Find := I; Exit;
end;
if (K = 0) and ((S[I] = '*') or (S[I] = '/')) then K := I;
if S[I] = '(' then I := RightBracket(S, I);
Inc(I);
end;
Find := K;
end;
function DeleteBracket(S: string; var P: Char): string;
{剔除多余括号,S表示要处理的表达式;P表示表达式中最后一个运算符}
var
I: Byte;
Ch1, Ch2: Char;
Left, Right: string;
begin
if Length(S) = 1 then begin {当表达式中无运算符}
DeleteBracket := S; P := ' ';
Exit;
end;
if (S[1] = '(') and (RightBracket(S, 1) = Length(S)) then begin
{当表达式最外层有括号}
DeleteBracket := DeleteBracket(Copy(S, 2,Length(S)- 2), P);
Exit;
end;
I := Find(S); {找到最低运算符}
P := S[I];
Left := DeleteBracket(Copy(S,1,I- 1), Ch1);
{递归处理运算左边}
Right := DeleteBracket(Copy(S,I+1,Length(S)-I),Ch2);
{递归处理运算右边}
if (P in ['*', '/']) and (Ch1 in ['+', '-']) then
Left := '(' + Left + ')';
if (P in ['*','/'])and(Ch2 in ['+','-']) or
(P ='/')and(Ch2 <>' ') then
Right := '(' + Right + ')';
DeleteBracket := Left + P + Right;
end;
Begin
Assign(Input, Inp); Reset(Input);
Readln(Expr);
Assign(Output, Outp); Rewrite(Output);
Writeln(DeleteBracket(Expr, Ch));
Close(Input); Close(Output);
End.
测试数据
a+b(+c) a+b+c
(a*b)+c/(d*e) a*b+c/(d*e)
a+b/(c-d) a+b/(c-d)