模式匹配算法

时间:2011-06-18 18:08:32

标签: java algorithm

这是我大学课堂上的幻灯片,它关于模式匹配Algotithm ..  enter image description here

我尝试用Java编写代码;

            // Get values for both the text T1,T2 ... Tn and the pattern P1 P2 ... Pm
            String[] T = {"Java", "is", "too", "delicious", ", Dr.Java", "is", "confrim!"};
            String[] P = { "is", "too"};
            // Get values for n and m, the size of the text and the pattern, respectively
            int n = T.length;
            int m = P.length;
            // Set k1 the starting location for the attempted match, to 1
            int k = 0;

            // While(k<=(n-m+1))do
            while (k <= (n - m + 1) - 1) {
                    // Set the value of i to 1
                    int i = 0;
                    // Set the value of Mismatch NO
                    boolean Mismatch = true; // Not found (true - NO)

                    // While both (i<=m) and (Mismatch = NO) do
                    while ((i <= m - 1) && (Mismatch)) { // if Not found (true - NO)
                            // if Pi != Tk+(i-1) then
                            if (P[i].equals(T[k])) { // if Found(true)
                                    // Set Mismatch to YES
                                    Mismatch = false; // Found (false - YES)
                                    // Else
                            } else {
                                    // Increment i by 1 (to move to the next character)
                                    i = i + 1;
                            }
                            // End of the loop
                    }
                    // If mismatch = NO then
                    if (!Mismatch) { // if Found (false - YES)
                            // Print the message 'There is a match at position'
                            System.out.print("There is a match at position ");
                            // Print the value of k
                            System.out.println(k);
                    }
                    // Increment k by 1
                    k = k + 1;
                    // Enf of the loop
            }
            // Stop, we are finished

但我有一个问题!为什么在伪代码版本中,检查P是否不等于T?我认为它宁愿检查P是否等于T(我的版本与它有什么区别?对不起我可怕的英文)

2 个答案:

答案 0 :(得分:3)

你在内心时犯了翻译错误

while ((i <= m - 1) && (Mismatch)) { // if Not found (true - NO) 

在伪代码中,据说是Mismatch=no !Mismatch

这导致您必须反转内部if语句。

答案 1 :(得分:1)

伪代码基本上从每个点检查匹配可能在T(1 <= k <= n-m+1)中开始,循环并检查T的子串从k到k + m-1是否匹配P.所以一旦它找到一个不匹配的字母,它停止检查子字符串,并递增k(从下一个位置检查)。条件(T[k+i-1] != P[i])是内循环的中断条件,而布尔值从当前起始位置k标记,没有匹配。

请注意,此算法的复杂度O(nm)很慢。有更智能的算法可以在线性时间内搜索,如KMP。

相关问题