求一配对算法怎么检错,集思广益

求一配对算法如何检错,集思广益
如:begin与end需配对使用,
  begin
    begin

    end
  end
  begin
  end
如何检查出是否配对正确,错误情形很多,
  1、缺少end与之配对
  begin
  //end
  2、缺少begin与之配对
  //begin
  end
  3、多end或者多begin
  begin
  begin
  end
  end
  end
  类似这些错误,如何检查出这些错误呢
------解决方案--------------------
最基本的,一个栈,遇到Begin压栈,遇到end弹栈.
------解决方案--------------------
引用:
最基本的,一个栈,遇到Begin压栈,遇到end弹栈.
求一配对算法怎么检错,集思广益
------解决方案--------------------
引用:
最基本的,一个栈,遇到Begin压栈,遇到end弹栈.

差不多吧,当栈里面没有东西还要popup就报错,更简单的可以用一个变量
i:=0;
while file is not EOF do
begin
    read next word;
    if next word is 'begin' then
      i:=i+1;
    if next word is 'end' then
      i:= i-1;
    if i<0 then
     raise error
end;
麻烦的倒是要先清注释,再清掉字符串常量
------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:

最基本的,一个栈,遇到Begin压栈,遇到end弹栈.

差不多吧,当栈里面没有东西还要popup就报错,更简单的可以用一个变量
i:=0;
while file is not EOF do
begin
    read next word;
    if next word is 'begin' then
      i:=i+1;
    if next word is 'end' then
      i:= i-1;
    if i<0 then
     raise error
end;
麻烦的倒是要先清注释,再清掉字符串常量




这样还是有问题吧,如
begin
end
end
end
end
begin
begin
begin
检测不出来的,应该是楼上说的就近原则,最近的begin配最近的end,程序用什么算法好实现呢?

它在第2个end的地方i就小于0了,然后直接raise error
------解决方案--------------------
引用:
Quote: 引用:

还要考虑 字符串、注释 里的begin/end


这个不用考虑的,代码是生成,不会有注释


代码是生成?
那就好办了,每个begin/end后增加一套 {guid}
包好!
------解决方案--------------------
引用:
Quote: 引用:

最基本的,一个栈,遇到Begin压栈,遇到end弹栈.

差不多吧,当栈里面没有东西还要popup就报错,更简单的可以用一个变量
i:=0;
while file is not EOF do
begin
    read next word;
    if next word is 'begin' then
      i:=i+1;
    if next word is 'end' then
      i:= i-1;
    if i<0 then
     raise error
end;
麻烦的倒是要先清注释,再清掉字符串常量


最后再加一个判断,
if i>0 then //begin太多