如何以最快的方式做到这一点? [英] How to do this the fastest way?

查看:179
本文介绍了如何以最快的方式做到这一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找出一个单词在字符串中出现了多少次,但是要注意的是,你需要找到的单词之间可以有空格,例如你想看看单词 text 出现在* tOeOxOt,它会给你输出1,或例如在 textt 它会给你输出2,我已经写了这个程序在帕斯卡这个

$ b过程搜索(x:整数; i:整数);
var
x2:整数;
begin

 如果myarray [x2] = mystring [i + 1],那么
; = x + 1;
,而(x2 <= n)和(x2> 0)则开始
if i = length(mystring)-1 then
final:= final + 1
else
search(x2,i + 1);

x2:= x2 + 1;
end;
end;

从一个字母出现,例如,如果我有ttext 它只会给我一个,因为我只检查从第一个 t ,所以我每次找到一个 t g,但是这个方法对于有很多字符的二维数组来说太慢了,比如1000x1000,所以我正在寻找一个更快的解决方案。 解决方案

你可以检查数组两次,在第一次运行槽删除所有空格。
第二个使用像这样的比较函数(x是您搜索的数组,y是您正在搜索的子字符串,i是您正在检查的当前元素):
b
$ b

 函数比较(var x,y:myarray; i:integer):boolean; 
var l:integer;
开始
比较:= false;
for l:= 1 to length(y)do begin
如果x [i + 1]< y [l]然后退出;
结束;
比较:= true;
结束;

放在您数组的每个元素上。


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.

解决方案

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.

这篇关于如何以最快的方式做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆