Leetcode_28_Implement strStr

时间:2022-08-12 21:48:04

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41452047

Implement strStr().

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

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

这道题很简单,这里就不啰嗦了。下面给出我自己的解题算法和网站上给出公认的性能比较好的算法,显然,我写的算法还不够好,仅仅作为参考,希望对大家有所帮助。

本人的解题代码如下:

public int strStr(String hack, String need) {
	int needlen = need.length();
	int hacklen = hack.length();
	if (needlen == 0)
		return 0;
	if (needlen == 0 && hacklen == 0 || needlen > hacklen)
		return -1;

	for (int i = 0; i < hacklen; i++) {
		int y = needlen;
		int x = i;
		if (y <= hacklen) {
			y = y + i;
			if (y > hacklen)
				return -1;
			String compare = hack.substring(x, y);
			if (need.equals(compare)) {
				return x;
			}
		}
	}
	return -1;
}

网站上公认比较好的解题代码如下:

public 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;
		}
	}
}