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時給出這個答案,是明智的做法,還是我只是在吹捧自己的機會?
String str =「appleappleappleapple」; String pattern =「apple」; 這裏證明了一點! – CodeHunter