【题目描述】Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
字符串中第一次出现给定字符串的位置
【解题思路】首先要做一些判断,如果子字符串为空,则返回0,如果子字符串长度大于母字符串长度,则返回-1。然后我们开始遍历母字符串,我们并不需要遍历整个母字符串,而是遍历到剩下的长度和子字符串相等的位置即可,这样可以提高运算效率。然后对于每一个字符,我们都遍历一遍子字符串,一个一个字符的对应比较,如果对应位置有不等的,则跳出循环,如果一直都没有跳出循环,则说明子字符串出现了,则返回起始位置即可。
【考查内容】字符串
class Solution {
public:
char *strStr(char *haystack, char *needle) {
string str1(haystack);
int m=str1.size(); //母字符串长度
string str2(needle);
int n=str2.size(); //子字符串长度
if(m<n)
return NULL;
int i,j;
for(i=0;i<=m-n;i++){
for(j=0;j<n;j++){
if(str1[i+j] != str2[j])
break;
}
if(j==n)
return haystack+i; //字符串指针指向首字符;
}
return NULL;
}
};