如何判断一个算数表达式正确与否?(300分)

我覺得他們寫的都好復雜呀,是否可以用算數移位運算來做呢?
 
to 老人家:
呵呵,我用的方法是个笨办法,是用了递归,但没有用栈,哪里来的出栈进栈?
 
to LeeChange,
哦,抱歉我都没看你的代码(只看了2秒钟)
就下了结论(犯了经验主义)
呵呵
留个qq吧
 
to 老人家:
呵呵,大家都一样,我也是只看自己的,creation-zy的代码也没仔细研究.只测了几组数据而已.
呵呵,通病.
很高兴认识你.
看到后请回帖.
 
creation-zy, A1+B1+ 判断错误
 
呵呵,测的真仔细.
 
function IsValidExpression(ExprStr:String):Boolean;
const
Alpha_Number=['0'..'9','A'..'Z','a'..'z','_'];
Number=['0'..'9'];
CalChar=['+','-','*','/'];
type
TLastStatus=(lsCalChar,lsVariable,lsBracketbegin
,lsBracketEnd);
var
i,n,BracketCount,Len:Integer;
ch:Char;
Str:String;
LastStatus:TLastStatus;
begin
Result:=false;
Len:=Length(ExprStr);
i:=1;
BracketCount:=0;
LastStatus:=lsCalChar;
//初始化为运算符
while i<=Lendo
begin
ch:=ExprStr;
if ch in ['a'..'z','A'..'Z','_'] then
//变量
begin
if LastStatus in [lsVariable,lsBracketEnd] then
// "a1 b2" or ")d5"
exit;
if ch in ['a'..'g','A'..'G'] then
begin
Str:='';
Inc(i);
while i<=Lendo
begin
ch:=ExprStr;
if ch in Alpha_Number then
Str:=Str+ch
else
//变量名结束
break;
Inc(i);
end;
n:=StrToIntDef(Str,-1);
if (n<1) or (n>100) then
exit;
end
else
//变量名不是以 a..g 开头
exit;
LastStatus:=lsVariable;
end
else
if ch in Number then
//数字
begin
if LastStatus in [lsVariable,lsBracketEnd] then
// "a1 5" or "4 9"
exit;
Inc(i);
while i<=Length(ExprStr)do
begin
ch:=ExprStr;
if not (ch in Number) then
break;
Inc(i);
end;
if ch='.' then
//数字后紧跟着小数点...
begin
Inc(i);
while i<=Lendo
begin
ch:=ExprStr;
if not (ch in ['0'..'9']) then
break;
Inc(i);
end;
if ch='.' then
//数字中有两个小数点
exit;
end;
LastStatus:=lsVariable;
end;
if i>Len then
break;
case ch of
'(': //括号计算
begin
if LastStatus in [lsVariable,lsBracketEnd] then
// "12(" or ")("
exit;
Inc(BracketCount);
LastStatus:=lsBracketbegin
;
end;
')': //括号计算
begin
Dec(BracketCount);
if BracketCount<0 then
//出现了右括号比左括号多的情况...
exit;
if LastStatus in [lsBracketbegin
,lsCalChar] then
// () or +)
exit;
LastStatus:=lsBracketend;
end;
else
begin
if ch in CalChar then
begin
if LastStatus in [lsBracketbegin
,lsCalChar] then
// (+ or *-
exit;
LastStatus:=lsCalChar;
end
else
if ch>' ' then
//其它可见字符——表达式中有非法字符
exit;
end;
end;
Inc(i);
end;
//括号数量正确 and 以变量或右括号结束
Result:=(BracketCount=0) and (LastStatus in [lsVariable,lsBracketEnd]);
end;
 
接受答案了.
 
顶部