class Solution { public: int strStr(string haystack, string needle) { if(needle.empty())return 0; //needle empty if(haystack.empty()) return -1; //haystack empty for(int i = 0, j = 0; i+j < haystack.size();) { if(haystack[i+j] != needle[j])i++, j = 0; //no equal needle index to 0, haystack index move to next. else j++; //equal both move to next if(j == needle.size())return i; //thr first time find substr. } return -1; } };
本文提供了一个C++实现的字符串查找算法示例,通过遍历主串并逐字符对比目标子串来寻找首次出现的位置。该算法考虑了特殊情况如目标为空字符串的情况。
410

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



