Implement strStr()

来源:互联网 发布:为知笔记登陆 编辑:程序博客网 时间:2024/05/18 00:47

这是算法中比较经典的问题,判断一个字符串是否是另一个字符串的子串。这个题目最经典的算法应该是KMP算法.KMP算法是最优的线性算法,复杂度已经达到这个问题的下限。但是KMP算法比较复杂,很难在面试的短时间里面完整正确的实现。

下面介绍两种解题方法:(1)brute force (2)KMP

(1)brute force 

public static int strStr(String haystack, String needle) {for(int i=0;;i++){for(int j=0;;j++){if(j==needle.length())return i;if(i+j==haystack.length())return -1;if(needle.charAt(j)!=haystack.charAt(i+j))break;}}    <span style="white-space:pre"></span>}
(2)KMP

static void getNext(String str,int next[]){int i=0,j=-1;next[0]=-1;while(i<str.length()){if(j==-1||str.charAt(i)==str.charAt(j)){i++;j++;next[i]=j;}else {j=next[j];}}}public static int strStrKMP(String haystack, String needle,int pos) {int []next=new int[haystack.length()];getNext(needle, next);int i=pos,j=0;while(i<haystack.length()&&j<needle.length()){if(j==-1||haystack.charAt(i)==needle.charAt(j)){i++;j++;}elsej=next[j];}if(j>=needle.length())return i-needle.length();elsereturn 0;    }

0 0
原创粉丝点击