028 Implement strStr() 实现 strStr()

实现 strStr()。
返回蕴含在 haystack 中的 needle 的第一个字符的索引,如果 needle 不是 haystack 的一部分则返回 -1 。
例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
详见:https://leetcode.com/problems/implement-strstr/description/

Java实现:

方法一:暴力解

class Solution {
    public int strStr(String haystack, String needle) {
        int hsize=haystack.length();
        int nsize=needle.length();
        int i=0;
        int j=0;
        while(i<hsize&&j<nsize){
            if(haystack.charAt(i)==needle.charAt(j)){
                ++i;
                ++j;
            }else{
                i=i-j+1;
                j=0;
            }
        }
        if(j==nsize){
            return i-j;
        }else{
            return -1;
        }
    }
}

方法二:KMP算法

class Solution {
    public int strStr(String s, String p) {
        int i=0;
        int j=-1;
        int ps=p.length();
        int[] next=new int[ps+1];
        next[0]=-1;
        while(i<ps){
            if(j==-1||p.charAt(i)==p.charAt(j)){
                ++i;
                ++j;
                next[i]=j;
            }else{
                j=next[j];
            }
        }
        int ss=s.length();
        i=0;
        j=0;
        while(i<ss&&j<ps){
            if(j==-1||s.charAt(i)==p.charAt(j)){
                ++i;
                ++j;
            }else{
                j=next[j];
            }
        }
        if(j==ps){
            return i-j;
        }
        return -1;
    }
}
原文地址:https://www.cnblogs.com/xidian2014/p/8687431.html