題目:
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
思路:暴力解決:public String strStr(String haystack, String needle) {
if (needle == null || haystack == null)
return null;
if (haystack.length() == 0 && needle.length() == 0)
return haystack;
if (needle.length() == 0)
return haystack;
for (int i = 0; i < haystack.length() - needle.length()+1; i++) {
if (haystack.charAt(i) == needle.charAt(0)) {
int x = i + 1;
int j = 1;
boolean flag = true;
while (x < haystack.length() && j < needle.length()) {
if (haystack.charAt(x) == needle.charAt(j)) {
x++;
j++;
} else {
flag = false;
break;
}
}
if (flag)
return haystack.substring(i);
}
}
return null;
}