![](/img/trans.png)
[英]Is it possible to use Google Docs API to convert text string to PDF
[英]Is it possible to use Knuth-Morris-Pratt Algorithm for string matching on text to text?
我在PHP中有一個KMP代碼,可以在單詞到文本之間進行字符串匹配。 我想知道我是否可以使用KMP算法在文本之間進行字符串匹配。 有沒有可能? 以及如何使用它來查找2個文本之間的字符串匹配。
這是KMP算法的核心:
<?php
class KMP{
function KMPSearch($p,$t){
$result = array();
$pattern = str_split($p);
$text = str_split($t);
$prefix = $this->preKMP($pattern);
// print_r($prefix);
// KMP String Matching
$i = $j = 0;
$num=0;
while($j<count($text)){
while($i>-1 && $pattern[$i]!=$text[$j]){
// if it doesn't match, then uses then look at the prefix table
$i = $prefix[$i];
}
$i++;
$j++;
if($i>=count($pattern)){
// if its match, find the matches string potition
// Then use prefix table to swipe to the right.
$result[$num++]=$j-count($pattern);
$i = $prefix[$i];
}
}
return $result;
}
// Making Prefix table with preKMP function
function preKMP($pattern){
$i = 0;
$j = $prefix[0] = -1;
while($i<count($pattern)){
while($j>-1 && $pattern[$i]!=$pattern[$j]){
$j = $prefix[$j];
}
$i++;
$j++;
if(isset($pattern[$i])==isset($pattern[$j])){
$prefix[$i]=$prefix[$j];
}else{
$prefix[$i]=$j;
}
}
return $prefix;
}
}
?>
如果我想用來在文本上查找單詞,我會將該類調用到我的index.php。
這是我要我的代碼執行的步驟:(1)。 我輸入了文本1(2)。 我輸入了文本2(3)。 我希望文本1成為模式(文本1中的每個單詞都視為模式)(4)。 我希望我的代碼可以找到文本2(5)中文本1上的每個模式。 最后,我的代碼可以向我展示相似度的百分比。
希望大家能幫助我或教我。 我一直到處都在尋找答案,但是還找不到。 至少你可以教我。
如果只需要查找兩個文本中都存在的所有單詞,則不需要任何字符串搜索算法。 您可以將第一個文本中的所有單詞添加到哈希表中,遍歷第二個文本,並將哈希表中的單詞添加到輸出列表中。
如果在最壞的情況下想要線性的時間復雜度,則可以使用trie代替哈希表,但是我將開始使用哈希表,因為它易於使用,並且可能足以滿足實際用途。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.