【问题描述】
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
【思路】
本题的目的其实是实现函数String.indexof()
即:return haystack.indexOf(needle);
维护两个指针,依次扫描haystack与needle。
【code】
public class Solution {
public int strStr(String haystack, String needle) {
//return haystack.indexOf(needle);
if (haystack.length() < needle.length()) {
return -1;
}
if (needle.length() == 0) {
return 0;
}
if (haystack.length() == 0) {
return -1;
}
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
if (haystack.charAt(i) == needle.charAt(0)) {
int j = 0;
for (j = 0; j < needle.length(); j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) {
break;
}
}
if (j != needle.length()) {
continue;
} else {
return i;
}
}
}
return -1;
}
}