题目描述: 实现strStr()
实现 strStr()。
返回蕴含在 haystack 中的 needle 的第一个字符的索引,如果 needle 不是 haystack 的一部分则返回 -1 。
例 1:
输入: haystack = "hello", needle = "ll" 输出: 2
例 2:
输入: haystack = "aaaaa", needle = "bba" 输出: -1
代码:
class Solution {
public:
int strStr(string haystack, string needle) {
if(haystack.size() == 0&&needle.size() != 0) return -1;
int l1=haystack.size();
int l2=needle.size();
for(int i = 0 ; i <= l1-l2; i++){
int flag = 1;
for(int j = 0 ; j < needle.size() ; j ++) {
if(haystack[i+j] != needle[j]) {
flag =0;
break;
}
}
if(flag) return i;
}
return -1;
}
};