How to do this the fastest way?

2019-02-20 03:56发布

I need to find out how many time one word appears in the string, but the catch is that the word you need to find can have spaces in between, for example you want to see how many times word text appears in *tOeOxOt" and it would give you output 1, or for example in textt it would give you output 2, I have written this procedure in pascal for this

procedure search(x:integer; i:integer);
var
x2:integer;
begin
x2:=x+1;
while (x2<=n) and (x2>0) do begin
    if myarray[x2]=mystring[i+1] then
        if i=length(mystring)-1 then
        final:=final+1
        else
        search(x2,i+1);

x2:=x2+1;
end;
end;

and it checks number of time it appears from one letter, for example if I have ttext it would only give me one because I only check from the first t so I call the function every time I find a t in the string, but this method is too slow for 2D arrays with many characters, like 1000x1000 so I am looking for a faster solution.

1条回答
Deceive 欺骗
2楼-- · 2019-02-20 04:40

You could check the array twice, on the first run trough it remove all spaces. On the second one use a compare function like this(x is the array in which you search, y is the sub-string you are searching for and i is the current element you are checking):

function compare(var x,y:myarray; i:integer):boolean;
var l:integer;
Begin
  compare:=false;
  for l:=1 to length(y) do Begin
    if x[i+l] <> y[l] then Exit;
  End;
  compare:=true;
End;

on each element of your array.

查看更多
登录 后发表回答