2017-02-11 61 views
1

我试图编码KMP算法。完成后,我使用java字符串方法尝试了它。这里是我是如何实现:这种模式发现方法是否比KMP或Z算法实现更好?

String str = "This is easier version of fist"; 
    String pattern = "is"; 
    String[] splitStr = str.split(pattern); 
    System.out.println("Total occurence of the given pattern in the given string is =" 
      +(splitStr.length-1)); 
    int i=1, count=0; 
    for(String st: splitStr){ 
     if(i<splitStr.length){ 
     count += st.length(); 
     System.out.println("Occurence of "+i+" pattern is at index "+count); 
     count+=pattern.length(); 
     i++; 
     } 
    } 

我得到以下的输出:

Total occurence of the given pattern in the given string is =3 
Occurence of 1 pattern is at index 2 
Occurence of 2 pattern is at index 5 
Occurence of 3 pattern is at index 27 

我知道的Java分裂的那段时间复杂度()方法是O(字符串长度)。上述代码如何公平对待KMP实施? 另外,如果我在采访模式匹配案例而不是KMP时给出这个答案,是明智的做法,还是我只是在吹捧自己的机会?

回答

1

编辑:我解决了我以前的复杂度计算。

KMP实现以复杂度O(n + m)运行,其中n = str.length()和m = pattern.length()。

您的算法也运行复杂度为O(n + m),但它可以跳过正确的匹配并产生错误的答案。

考虑这个测试用例:

String str = "apple-orange-apple-apple-apple-orange-apple"; 
String pattern = "apple"; 

你的代码产生4个出现次数。它应该是5对吗?

而这种情况:

String str = "appleappleappleapple"; 
String pattern = "apple"; 

我认为这不是吹你的机会,因为它表明你能够在Java代码中你的逻辑,并与解决方案出来。

祝您在面试中好运。

+0

String str =“appleappleappleapple”; String pattern =“apple”; 这里证明了一点! – CodeHunter

相关问题