[Link] https://leetcode.com/problems/implement-strstr/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int strStr(String haystack, String needle) {
int hayIdx = 0, needleIdx = 0, nlen = needle.length(), lenDiff = haystack.length() - nlen;
char[] hay = haystack.toCharArray(), need = needle.toCharArray();
if(needle.length() == 0) return 0;
while(hayIdx <= lenDiff) {
int hayIdxCp = hayIdx;
needleIdx = 0;
for(int i = 0; i < needle.length(); i++) {
if(hay[hayIdxCp++] != need[i]) break;
if(i == nlen - 1) return hayIdx;
}
hayIdx++;
}
return -1;
}
}