挺经典的一道问题,写下来供以后复习。
题目:对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1
。
样例:
如果 source = "source"
和 target = "target"
,返回 -1
。
如果 source = "abcdabcdefg"
和 target = "bcd"
,返回 1
。
实现:
class Solution {
public:
/*
* @param source: source string to be scanned.
* @param target: target string containing the sequence of characters to match
* @return: a index to the first occurrence of target in source, or -1 if target is not part of source.
*/
/*int strStr(const char *source, const char *target) { //注释的这部分使用的是普通的搜索方法
// write your code here
if(source == NULL || target == NULL)
return -1;
int m = strlen(source), n = strlen(target);
if(m == 0 && n == 0)
return 0;
int result, label = 0;
for(int i = 0; i < m; i++){
int l = i, j = 0;
while(source[l] == target[j] && j < n){
l++, j++;
}
if(j == n){
result = i;
label = 1;
break;
}
}
if(label == 1)
return result;
else
return -1;
}*/
int strStr(const char *source, const char *target){ //这部分是使用的KMP算法来解决
if(source == NULL || target == NULL)
return -1;
int len = strlen(source);
int len1 = strlen(target);
if(len1 == 0)
return 0;
if(len == 0)
return -1;
int i = 0;
vector<int> next(len1);
kmpNext(target, next);
while(i < len){
int j = 0;
int l = i;
while(j < len1 && source[l] == target[j]){
l++, j++;
}
if(j == len1)
//delete ;
return i;
else
i += j - next[j];
}
return -1;
}
void kmpNext(const char *source, vector<int> &next){ //这里是求next[]
next[0] = -1;
int len = strlen(source);
for(int i = 1; i < len; i++){
int j = next[i - 1];
while (j >= 0 && source[i - 1] != source[j])
j = next[j];
if(j >=0 && source[i - 1] == source[j])
next[i] = j + 1;
else
next[i] = 0;
}
}
};
积累积累。