【问题标题】:Evaluating the time efficiency of KMP algorithm on list of objects评估 KMP 算法在对象列表上的时间效率
【发布时间】:2019-12-23 10:56:02
【问题描述】:

我在我的程序中实现了 KMP 模式搜索算法来搜索对象表。我想知道如何评估我的函数的时间效率。

我看了一些资料,说KMP算法的时间复杂度是O(n) [不包括空间复杂度]

所以我将遍历从 1 到 N 项的对象列表,在每个项中搜索模式匹配。一旦有比赛,我会跳出循环,但这并不会真正影响我的评估(我认为)。

因此,由于我迭代了所有项目,所以我的大 O 符号是:O(n^2) 因为它需要 O(n) 找到匹配项并 O(n) 遍历我的所有项目。

这是我的一些见解代码:

while(itr.hasNext()){
    //M is the length of our pattern

    i = 0; //index of text to be searched
    j = 0; //index of our pattern

    txt  = itr.next().toString();  //Store the key inside txt string
    N = txt.length(); //length of our text to be search
    
    //Check if the searchText is equal or less than key in the dictionary
    //If our searchText is more than the key length, there is no use of searching
    if(M <= N){
        while (i < N) {
            //Check if the searchText.charAt equals to txt.charAt
            //Increase i,j if matches to compare next character(s)
            if (searchText.charAt(j) == txt.charAt(i)) { 
                j++; 
                i++; 
            }else{ //If the chars at our pattern and text does not match
                if (j != 0) //if it's not the first index of our pattern
                    j--; //reduce one index
                else
                    i++; //otherwise move onto the next index of our text to be searched
            }
            
            //Check whether the length of the searchText equals to the match counter
            //It means that the searchKey exists in our dictionary
            if (j == M) { 
                System.out.println((String.format("%-35s", txt)) + get((K)txt));
                counter++;      //Holds the number of entries found
                j--; 
                break;          //No need to look anymore since there's a match
            }
        }
    }
}

【问题讨论】:

  • jnext 是如何定义的?我假设 next 是 KMP 部分匹配表,j 是该表的索引。 KMP 算法本身具有最坏情况和平均时间复杂度O(length of txt)。如果对itr 的每个元素运行该算法,则程序将具有最坏情况时间复杂度O((length of itr)*max(length of txt in itr)) 和平均时间复杂度O((length of itr)*average(length of txt in itr))。跳出循环只会影响最佳情况的时间复杂度(模式立即在第一个txt 中找到),即O(length of searchText)

标签: java algorithm pattern-matching big-o knuth-morris-pratt


【解决方案1】:

如果您的列表中有 n 个项目并且平均每个元素大小为 m,那么搜索时间复杂度将为 O(mn)。对于每个元素,KMP 的搜索时间复杂度为 O(m)。你需要将它乘以 n。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2019-04-03
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多