就是检查括号()[]{}之间的匹配情况
如果文件很大的话,如何快速的找出是否匹配正确?
a.t.t 3x

解决方案 »

  1.   

    program Project2;{$APPTYPE CONSOLE}uses
      SysUtils,
      Contnrs;type
      TCharStack = class(TStack)
      private
        function GetTop: Char;
      public
        function Pop: Char;
        function Push(Item: Char): Char;
        property Top: Char read GetTop; 
      end;{ TCharStack }function TCharStack.GetTop: Char;
    begin
      Result := Char(Peek);
    end;function TCharStack.Pop: Char;
    begin
      Result := Char(inherited Pop);
    end;function TCharStack.Push(Item: Char): Char;
    begin
      Result := Char(inherited Push(Pointer(Item)));
    end;function FindFirstOf(const Str: String; const CharSet: TSysCharSet; StartPos: Integer = 1): Integer;
    begin
      Result := StartPos;
      while (Result <= Length(Str)) and not (Str[Result] in CharSet) do
        Inc(Result);
      if Result > Length(Str) then
        Result := 0;
    end;const
      NPos = 0;
      FindSet = ['(',')','{','}','[',']'];
    var
      Stack: TCharStack;
      Line: String;
      Inf: TextFile;
      Pos: Integer;
      LineNumber: Integer = 0;  procedure Check;
      begin
        while not Eof(inf) do
        begin
          ReadLn(inf, Line);
          Pos := FindFirstOf(Line, FindSet);
          while(Pos <> NPos) do
          begin
            case Line[Pos] of
              '(', '[', '{':
                Stack.Push(Line[Pos]);
              ')':
                if (Stack.Count = 0) or (Stack.top <> '(') then
                begin
                  WriteLn('Error:', LineNumber, ':', Copy(Line, 1, Pos));
                  Halt;
                end
                else
                  Stack.Pop();
              ']':
                if (Stack.Count = 0) or (Stack.top <> '[') then
                begin
                  WriteLn('Error:', LineNumber, ':', Copy(Line, 1, Pos));
                  Halt;
                end
                else
                  Stack.Pop();
              '}':
                if (Stack.Count = 0) or (Stack.top <> '{') then
                begin
                  WriteLn('Error:', LineNumber, ':', Copy(Line, 1, Pos));
                  Halt;
                end
                else
                  Stack.Pop();
            end;
            Pos := FindFirstOf(Line, FindSet, Pos +1);
          end;
          Inc(LineNumber);
        end;
        if Stack.Count > 0 then
          WriteLn('Error!')
        else
          WriteLn('OK!');
        ReadLn;
      end;
    begin
        AssignFile(inf, 'e:\utilcls.h');
        Reset(Inf);
        Stack := TCharStack.Create;
        try
          Check;
        except
        end;
        Stack.Free;
        CloseFile(Inf);
    end.