不得不说,算法这种东西,不用很容易忘,幸好KMP当时潜心研究过,这题还是有惊无险的过了,抄一下题先:
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1
。
样例
样例 1:
输入: source = "source" , target = "target"
输出:-1
样例解释: 如果source里没有包含target的内容,返回-1
样例 2:
输入: source = "abcdabcdefg" ,target = "bcd"
输出: 1
样例解释: 如果source里包含target的内容,返回target在source里第一次出现的位置
挑战
O(n2)的算法是可以接受的。如果你能用O(n)的算法做出来那更加好。(提示:KMP)
接下来就是AC代码啦
class Solution {
public:
/**
* @param source:
* @param target:
* @return: return the index
*/
int strStr(string &source, string &target) {
// Write your code here