public class Solution {
public String strStr(String haystack, String needle) {
// Start typing your Java solution below
// DO NOT write main() function

if (needle.length() == 0) {//you can always find an empty string
return haystack;
}
if (haystack.length () < needle.length()) {
return null;
}

int i = 0, j = 0;
while(i < haystack.length() && j < needle.length()) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
if (j == needle.length()) {
return haystack.substring(i - j);
}
}
else {
i = i - j + 1;
j = 0;
}
}
return null;
}
}

Advertisements