leetcode 28. Implement strStr()

来源:互联网 发布:网络社群有哪些 编辑:程序博客网 时间:2024/06/13 10:53

问题:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

采用KMP模式匹配算法:主要参考   http://blog.csdn.net/v_july_v/article/details/7041827

public class Solution {    public static int[] getNext(String sub){        int[] next=new int[sub.length()];        int k=-1,j=0;        next[0]=-1;        while(j<sub.length()-1){            if(k==-1||sub.charAt(k)==sub.charAt(j)){                k++;                j++;                next[j]=k;            }else{                k=next[k];            }        }        return next;    }    public int strStr(String haystack, String needle) {        if(needle.equals(""))return 0;        if(haystack.equals(""))return -1;        int i=0,j=0;        int[] next=getNext(needle);         while(i<haystack.length()&&j<needle.length()){             if(j==-1||haystack.charAt(i)==needle.charAt(j)){                 i++;                 j++;             }else{                j=next[j];             }         }         if(j==needle.length()){             return i-j;         }else return -1;    }}





原创粉丝点击