首页 > 其他 > 详细

Implement strStr()

时间:2015-06-06 02:10:05      阅读:188      评论:0      收藏:0      [点我收藏+]

Implement strStr().

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

?

public class Solution {
	private static int[] nextval;
	private static void get_nextval(String needle) {
		nextval = new int[needle.length()+1];
		int i = 0;
		int j = -1;
		nextval[0] = -1;
		while (i < needle.length()-1) {
			if (j==-1 || needle.charAt(i)==needle.charAt(j)) {
				i++;
				j++;
				if (needle.charAt(i)==needle.charAt(j)) {
					nextval[i] = nextval[j];
				} else {
					nextval[i] = j;
				}
			} else {
				j = nextval[j];
			}
		}
	}
    public static int strStr(String haystack, String needle) {
    	get_nextval(needle);
        int i = 0;
        int j = 0;
        while (i<haystack.length() && j<needle.length()) {
        	if (j==-1 || haystack.charAt(i)==needle.charAt(j)) {
        		i++;
        		j++;
        	} else {
        		j = nextval[j];
        	}
        }
        if (j >= needle.length()) {
        	return i-needle.length();
        } else {
        	return -1;
        }
    }
}

?

Implement strStr()

原文:http://hcx2013.iteye.com/blog/2217366

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!