题目描述
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
Clarification:
we will return 0 when needle
is an empty string.
题目思路
代码 C++
- 思路一、
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle == ""){
return 0;
}
int a1 = haystack.size();
int a2 = needle.size();
int k, tt;
for(int i=0; i < a1; i++){
k = i;
tt = 0;
for(int j=0; j < a2 && k < a1 ; j++){
if(haystack[k] == needle[j]){
tt = tt + 1;
k = k + 1;
}
else{
break; // 跳出内层 for 循环
}
}
if(tt == a2){
return i;
}
}
return -1;
}
};
- 思路二、