题目链接:http://www.lintcode.com/zh-cn/problem/strstr/
问题描述:
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1
。
解决思路:采用双重for循环解决,思路清晰,代码较容易写,但效率不高,另外一种方法是用KMP算法,效率较高。需注意边界条件,
源代码
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
//source or target 为空 返回-1:
if(source==NULL||target==NULL){
return -1;
}
int i,j;
//计算source、target长度
int lens=strlen(source);
int lent=strlen(target);
for(i=0;i<lens-lent+1;i++){
j=0;
for(;j<lent;j++){
if(source[i+j]!=target[j]){
break;
}
}
if(j==lent){
return i;
}
}
return -1;
}
};