Implement strStr()
Description
For a given source string and a target string, you should output the first index(from 0) of target string in source string.
If target does not exist in source, just return
-1
.Clarification
Do I need to implement KMP Algorithm in a real interview?
- Not necessary. When you meet this problem in a real interview, the interviewer may just want to test your basic implementation ability. But make sure you confirm with the interviewer first.
Example
If source =
"source"
and target ="target"
, return-1
.If source =
"abcdabcdefg"
and target ="bcd"
, return1
.Challenge
O(n2) is acceptable. Can you implement an O(n) algorithm? (hint: 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) { } };
题目大意
给你两个字符串,源字符串和目标字符串。让你判断目标字符串在源字符串中的位置。
大概思路
最简单的方法就是O(n2)(n方)的算法了,直接两次遍历,找到相同的就可以
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) { if((!source) || (!target)) return -1; if((strlen(target) == 0)) return 0; int err = 1; for(int i=0; source[i]; i++){ if(source[i] == target[0]){ err = 0; for(int j=1; target[j]; j++){ if(source[i+j] != target[j]){ err = 1; break; } } } if(!err) return i; } return -1; } };
进阶思路
其实有O(n)的算法,只不过不太好弄,我尽量说明白。叫KMP算法,比较两个字符串中有名的算法,俗称“看毛片”算法。留坑明天补。
啊,补昨天的KMP,今天超级热。先上代码。具体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) { if((!source) || (!target)) return -1; if((strlen(target) == 0)) return 0; int F[1024]; F[0] = -1; int n=0, m=0, i, j; for(i=0; source[i]; i++) n++; for(i=0; target[i]; i++) m++; //初始化F数组 for(i=1; i<m; i++){ j = F[i-1]; while((target[j+1] != target[i]) && (j >= 0)) j = F[j]; if(target[j+1] == target[i]) F[i] = j+1; else F[i] = -1; } //对问题进行求解 j=0; i=0; while(i<n){ if(source[i] == target[j]){ i++;j++; if(j == m) return i-m; } else{ if (j == 0) i++; else j = F[j-1]+1; } } return -1; } };
KMP具体讲解博客地址 https://blog.csdn.net/qq_24889575/article/details/81812125
题目链接: https://www.lintcode.com/problem/implement-strstr/description