题目链接:https://leetcode.com/problems/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()
原文:http://blog.csdn.net/yeqiuzs/article/details/51590930