How to do this the fastest way?

。_饼干妹妹 提交于 2019-12-04 02:16:13

问题


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:


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.



来源:https://stackoverflow.com/questions/23034282/how-to-do-this-the-fastest-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!