[水]剔除多余括号

【问题描述】
键盘输入一个含有括号的四则运算表达式,可能含有多余的括号,编程整理该表达式,去掉所有多余的括号,原表达式中所有变量和运算符相对位置保持不变,并保持与原表达式等价。
例:

输入表达式  应输出表达式
a+(b+c)  a+b+c

(a*b)+c/d   a*b+c/d


a+b/(c-d)   a+b/(c-d)
注意输入 a+b 时不能输出 b+a。
表达式以字符串输入。
所有变量为单个小写字母。只是要求去掉所有多余括号,不要求对表达式化简。
【输入数据】
一个字符串,长度不超过 255,输入不要判错
【输出数据】
去掉所有多余括号后的表达式
【样例输入】
a+(b+c)
【样例输出】
a+b+c

 

经典水题。分治。

说来惭愧之前竟然没有写过。

20min水掉。

View Code
 1 program ub;
 2 
 3 Type
 4  rec=record
 5    st,ed:longint;
 6  end;
 7 
 8  Var
 9   s:string;
10 
11 Procedure fopen;
12   begin
13   assign(input,'ub.in');
14   assign(output,'ub.out');
15   reset(input);
16   rewrite(output);
17 end;
18 
19 Procedure fclose;
20   begin
21   close(input);
22   close(output);
23 end;
24 
25 Function havep(S:String):boolean;
26 var
27  deep,i:longint;
28   begin
29   havep:=false;
30   deep:=0;
31   for i:=1 to length(s) do
32     begin
33     if ( s[i] in ['+','-'] )  and (deep=0) then
34       exit(true);
35     if s[i]='(' then inc(deep);
36     if s[i]=')' then dec(deep);
37   end;
38 end;
39 
40 Function work(S:String):string;
41 var
42  ct,deep,i:longint;
43  ans,y:string;
44  a:array[0..300] of rec;
45  can:boolean;
46   begin
47   ct:=0;
48   deep:=0;
49   for i:=1 to length(s) do
50     if (s[i]='(') then
51       begin
52       inc(deep);
53       if deep=1 then begin inc(ct); a[ct].st:=i; end;
54     end else
55       if s[i]=')' then
56         begin
57         dec(deep);
58         if deep=0 then a[ct].ed:=i;
59       end;
60   if ct=0 then exit(s);
61   a[ct+1].st:=length(s)+1;
62   ans:=copy(s,1,a[1].st-1);
63   for i:=1 to ct do
64     begin
65     y:=work(copy(s,a[i].st+1,a[i].ed-a[i].st-1));
66     can:=true;
67     //fore
68     if (a[i].st>1) then
69       case s[ a[i].st-1 ] of
70         '-':if (length(y)>1) and havep(y) then can:=false;
71         '*':if havep(y) and (length(y)>1) then can:=false;
72         '/':if length(y)>1 then can:=false;
73       end;
74     //back
75     if a[i].ed<length(s) then
76       case s[ a[i].ed+1] of
77         '*':if havep(y) and (length(y)>1) then can:=false;
78         '/':if havep(y) and (length(y)>1) then can:=false;
79       end;
80     if can then ans:=ans+y else ans:=ans+'('+y+')';
81       ans:=ans+copy(s,a[i].ed+1,a[i+1].st-1-a[i].ed);
82   end;
83   exit(ans);
84 end;
85 
86   begin
87   fopen;
88   readln(s);
89   writeln(work(s));
90   fclose;
91 end.

转载于:https://www.cnblogs.com/htfy/archive/2012/10/25/2738732.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值