【Leetcode】Implement strStr()

题目链接:

题目:

Implement strStr().

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

算法:

	public int strStr(String haystack, String needle) {
		char h[] = haystack.toCharArray();
		char n[] = needle.toCharArray();
		int i = 0, j = 0;
		while (i < h.length && j < n.length) {
			if (h[i] == n[j]) {
				j++;
				i++;
			} else {
				i = i - j + 1;
				j = 0;
			}

		}
		if (j == n.length) {
			return i - needle.length();
		} else {
			return -1;
		}
	}


你可能感兴趣的:(【Leetcode】Implement strStr())