题目:
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
解题思路:我们需要一个比较的函数,将needle中的字符串与输入字符串中的子序列进行一一匹配,如果成功,则返回触发这个函数的位置。然后我们还需要一个触发比较的函数,一旦在输入字符串中发现当前位置的字符与needle中的第一个字符匹配,则触发比较。
代码如下:
class Solution {
public:
int strStr(string haystack, string needle) {
bool isFailed = 0;
for (int i = 0 ; i < haystack.length(); i++) {
isFailed = 0;
if (haystack[i] == needle[0]) {
for (int k = 0; k < needle.length(); k++) {
if (haystack[i+k] != needle[k] || i+k>= haystack.length()) {
isFailed = 1;
break;
}
}
if (isFailed == 0)
return i;
}
}
if (needle.length() == 0)
return 0;
return -1;
}
};