How to check if a string contains only valid parentheses (open close same type (), {}, []) in Pascal

1 Answer

0 votes
program ValidParentheses;

function StringContainsValidParentheses(s: string): Boolean;
var
  arr: array of Char; // Dynamic array to simulate a stack
  ch: Char;
  top: Integer;
begin
  SetLength(arr, 0); // Initialize the stack
  top := -1; // Represents the top of the stack (empty)

  for ch in s do
  begin
    if ch = '(' then
    begin
      Inc(top); // Move the stack pointer up
      SetLength(arr, top + 1);
      arr[top] := ')';
    end
    else if ch = '{' then
    begin
      Inc(top);
      SetLength(arr, top + 1);
      arr[top] := '}';
    end
    else if ch = '[' then
    begin
      Inc(top);
      SetLength(arr, top + 1);
      arr[top] := ']';
    end
    else if (top < 0) or (arr[top] <> ch) then
    begin
      Exit(False); // Return False if the stack is empty or mismatched
    end
    else
    begin
      Dec(top); // Pop the stack
    end;
  end;

  // If the stack is empty at the end, the parentheses are valid
  StringContainsValidParentheses := (top = -1);
end;

begin
  WriteLn(StringContainsValidParentheses('(){}[]'));       
  WriteLn(StringContainsValidParentheses('([{}])'));       
  WriteLn(StringContainsValidParentheses('(){}[]()(){}')); 
  WriteLn(StringContainsValidParentheses('(]'));           
  WriteLn(StringContainsValidParentheses('({[)]}'));       
end.



(*
run:

TRUE
TRUE
TRUE
FALSE
FALSE

*)

 



answered Apr 25, 2025 by avibootz
...