您的位置:首页 > 其它

LeetCode题解:Implement strStr()

2015-08-21 15:16 411 查看
Implement strStr().

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

题意:求needle代表的字符串在haystack字符串中第一次出现的位置

解决思路:

传统字符串匹配算法

KMP

代码:

public class Solution {
    private int[] getNext(char[] str){
        int[] next = new int[str.length];

        for(int i = 1;i < next.length;++i){
            int j = next[i];

            while(j > 0 && str[j] != str[i]){
                if(j == 1 && next[j] == 1){
                    j = 0;
                }else{
                    j = next[j];
                }
            }

            if(j > 0 || str[j] == str[i]){
                next[i] = j + 1;
            }
        }

        return next;
    }

    public int strStr(String haystack, String needle) {
        if(needle.length() == 0){
            return 0;
        }

        if(needle.length() <= haystack.length()){
            int[] next = getNext(needle.toCharArray());

            int i = 0;
            int j = 0;

            while(i < haystack.length()){
                if(haystack.charAt(i) == needle.charAt(j)){
                    ++i;
                    ++j;

                    if(j == needle.length()){
                        return i - j;
                    }
                }else if(j > 0){
                    j = next[j];
                }else{
                    ++i;
                }
            }
        }

        return -1;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: