Problem 6:
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
.
面试时可以问下是否必须用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 if(source == NULL || target == NULL)//判断是null的情况 return -1; int x = strlen(target);int y = strlen(source); int i = 0 ; int j = 0;int k = 0; // i is position of sourse; j is position of target;k is the length of marched string while(i<y){ while(source[i] == target[j] && j < x){//要加上j<x不然两个字符串完全一样时就会无限循环直到内存访问冲突 i++; j++; k++; }//若匹配则一直执行这个while 循环 if(k==x)//如果子串在source串中完全匹配,获取第一个匹配值i-k; return i-k; else if(k>0)//如果部分匹配,将j和k设为0,从子串第一个字符重新在source 串中寻找匹配,这里i不要自增,因为while循环里已经将i设为下一个需匹配的字符位置了 { j=0; k=0; } else{//如果k==0,那么两串尚未匹配,这时要注意i自增,否则无限循环 i++; } } if(k == 0 && x!= 0) return -1; else return 0; //子串是空串,返回0 } };因为一旦不匹配,source串需要后移一个位置,子串要从开头进行匹配,时间复杂度为O(mn),下篇讲解用KMP算法进行计算,希望能讲清楚。