【LeetCode】028. Implement strStr()

时间:2021-09-03 15:57:01

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

题解:

 class Solution {
public:
int strStr(string haystack, string needle) {
int pos = -;
int len1 = haystack.size(), len2 = needle.size();
for (int i = ; i <= len1 - len2; ++i) {
int p1 = i, p2 = ;
while (p1 < len1 && p2 < len2) {
if (haystack[p1] != needle[p2])
break;
++p1;
++p2;
}
if (p2 == len2)
return i;
}
return -;
}
};