题目:strStr
要求:
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。
样例:
如果 source = "source" 和 target = "target",返回 -1。
如果 source = "abcdabcdefg" 和 target = "bcd",返回 1。
算法要求:
O(n2)的算法是可以接受的。如果你能用O(n)的算法做出来那更加好。(提示:KMP)
解题思路:
思路就是碰到开头一样的,即进入循环,一个一个比对,比对结束后,还原到比对开始的位置,如果比对结果正确,则范围此位置,否则继续比对。
学识薄浅,还没有学懂KMP,不敢随意造次,所以代码如下。
算法如下:
int strStr(const char *source, const char *target) {
int j = 0;
int i = 0;
if (source == NULL || target == NULL) {
return -1;
}
for (i = 0; source[i] != '\0'; i++) {
j = 0;
while (source[i] == target[j] && source[i] != '\0') {
j++;
i++;
}
if (target[j] == '\0') {
return i - j;
}
i -= j;
}
if (i == j && source[i] == target[j]) {
return i - j;
}
return -1;
}