LintCode 13. 字符串查找
问题描述
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。
样例
如果 source = “source” 和 target = “target”,返回 -1。
如果 source = “abcdabcdefg” 和 target = “bcd”,返回 1。
问题分析
最简单的做法就是暴力做法,从主串的第一个位置,将子串和主串对应长度的子串比较,不一样就将主串下一个字符当做开始位置,依次比较,这里我选择了效率很高的一种算法–Sunday,Sunday算法的高效在于有效的避免了一些不必要的比较,在字符串模式匹配中超越BF、KMP和BM的算法
代码
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 slen = strlen(source);
int tlen = strlen(target);
if(slen == 0 && tlen == 0)
return 0;
int next[256];
for (int i = 0; i < 256; i++) {
next[i] = -1;
}
for (int i =0; i < tlen; i++) {
next[target[i]] = i;
}
for (int i = 0; i <= slen - tlen;) {
int j = i;
int k = 0;
for(;k < tlen && j < slen && source[j] == target[k];j++,k++);
if(k == tlen)
return i;
else {
if(i+tlen < slen)
i += (tlen - next[source[i+tlen]]);
else
return -1;
}
}
return -1;
}
};
代码思路
比较难理解的是这条语句 i += (tlen - next[source[i+tlen]]);,这条语句的主要作用是找到子串需要进行的偏移量。下面的链接有具体的说明。