LeetCode28 Implement strStr()

时间:2023-03-09 03:18:36
LeetCode28 Implement strStr()

题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. (Easy)

分析:

不用考虑KMP啥的,就是写好暴力写法就行。

两重循环,注意空串判定,注意haystack比needle长,注意外层循环的终止条件。

代码:

 class Solution {
public:
int strStr(string haystack, string needle) {
if (haystack.size() == && needle.size() == ) {
return ;
}
if (haystack.size() < needle.size()) {
return -;
}
for (int i = ; i < haystack.size() - needle.size() + ; ++i) {
int flag = ;
for (int j = ; j < needle.size(); ++j) {
if (haystack[i + j] != needle[j]) {
flag = ;
break;
}
}
if (flag == ) {
return i;
}
}
return -;
}
};