Implement strStr()
Problem StatementImplement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Input: haystack = "hello", needle = "ll" Output: 2Solution
class Solution {
public int strStr(String haystack, String needle) {
char[] source = haystack.toCharArray();
char[] target = needle.toCharArray();
if (target.length == 0) {
return 0;
}
for (int i=0; i<source.length; i++) {
int t = 0;
int s = i;
while (source[s] == target[t] && i+target.length <= source.length) {
s++;
t++;
if (t==target.length) {
return i;
}
}
}
return -1;
}
}