Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
class Solution {
public:
int strStr(char *haystack, char *needle) {
int i,j;
for(i = 0,j = 0;haystack[i] && needle[j];){
if(haystack[i] == needle[j]){
i ++;
j ++;
}else{
i = i - j + 1;
j = 0;
}
}
return needle[j] == '\0' ? i - j : -1;
}
};
本文介绍了一个简单的 C++ 实现 strStr() 函数的方法,该函数用于查找子字符串首次出现的位置。通过遍历主字符串并与目标子字符串进行比较,实现快速定位。
332

被折叠的 条评论
为什么被折叠?



