2017-02-11 60 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

相關問題