#Leetcode# 28. Implement strStr()
https://leetcode.com/problems/implement-strstr/
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 l1 = haystack.length(), l2 = needle.length();
if(l2 > l1) return -1;
if(needle.empty()) return 0;
for(int i = 0; i <= l1 - l2; i ++) {
int cnt = 0;
for(int j = 0; j < l2; j ++) {
if(haystack[i + j] != needle[j]) break;
else cnt ++;
}
if(cnt == l2) return i;
}
return -1;
}
};

浙公网安备 33010602011771号