Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

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
...