How to check if a string can be constructed by using the letters of another string in Pascal

1 Answer

0 votes
program CanConstructProgram;

function CanConstruct(str, anotherstr: string): boolean;
var
  freq: array[0..255] of integer;
  i: integer;
  ch: byte;
begin
  { initialize frequency array }
  for i := 0 to 255 do
    freq[i] := 0;

  { count characters in anotherstr }
  for i := 1 to length(anotherstr) do
  begin
    ch := ord(anotherstr[i]);
    inc(freq[ch]);
  end;

  { check if str can be constructed }
  for i := 1 to length(str) do
  begin
    ch := ord(str[i]);
    dec(freq[ch]);
    if freq[ch] < 0 then
    begin
      CanConstruct := false;
      exit;
    end;
  end;

  CanConstruct := true;
end;

var
  s, t: string;

begin
  s := 'hello';
  t := 'olehhlxyz';

  if CanConstruct(s, t) then
    writeln('true')
  else
    writeln('false');
end.




(*
run:

true

*)


 



answered Jan 5 by avibootz

Related questions

...