描述:
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。
说明:
在面试中我是否需要实现KMP算法?
- 不需要,当这种问题出现在面试中时,面试官很可能只是想要测试一下你的基础应用能力。当然你需要先跟面试官确认清楚要怎么实现这个题。
样例:
如果 source = "source"
和 target = "target"
,返回 -1
。
如果 source = "abcdabcdefg"
和 target = "bcd"
,返回 1
。
挑战:
O(n2)的算法是可以接受的。如果你能用O(n)的算法做出来那更加好。(提示:KMP)
class Solution {
public:
/**
* Returns a index to the first occurrence of target in source,
* or -1 if target is not part of source.
* @param source string to be scanned.
* @param target string containing the sequence of characters to match.
*/
int strStr(const char *source, const char *target) {
// write your code here
if(source == NULL || target == NULL) //有字符串为NULL, 返回-1
return -1;
int souLen = strlen(source); //source字符串的长度
int tarLen = strlen(target); //target字符串的长度
if(tarLen == 0) //target长度为0(注意不为NULL) 返回起始位置为0
return 0;
if(tarLen > souLen) //target长度大于source长度,肯定不存在,返回-1
return -1;
//只需遍历到souLen - tarLen,超过这个值肯定不存在target
for(int i = 0; i <= souLen - tarLen; i++){
//若source当前字符和target第一个字符相等
//则继续判断从当前位起,是否每一位都和target的对应位相等
if(source[i] == target[0]){
int j = 0;
for(j = 0; j < tarLen; j++){
if(source[i + j] != target[j]) //不相等,跳出内循环
break;
if(j == tarLen - 1 && source[i + j] == target[j])
return i;
}
}
}
return -1;
}
};