int strStr(string haystack, string needle) {
if (needle.empty())
return 0;
//只有当needle字符串的长度小于或等于haystack字符串的长度才可能有公共区间
if (haystack.size() < needle.size())
return -1;
int index = -1;
for (int i = 0; i < haystack.size(); i++) {
string temp;
//haystack[i]等于needle字符串的第一个字符后面才可能出现公共子串
//i+needle.size()<=haystack.size()保证内层for循环下标不越界
if (haystack[i] == needle[0] && i + needle.size() <= haystack.size()) {
//记录开始的索引位置
index = i;
//将从位置i开始到needle.size()的长度字符全部截取到temp字符串
for (int j = i; j < i + needle.size(); j++)
temp.push_back(haystack[j]);
}
//temp字符串与needle字符串相等即从位置i开始有公共区间,直接跳出外层循环
if (temp == needle)
break;
else
index = -1;
}
return index;
}
28. 实现 strStr()
最新推荐文章于 2023-03-19 14:26:17 发布