28. Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题目比较简单,就是从字符串haystack中找出是否包含字符串needle,如果包含则返回匹配点的索引值,如果不包含则返回-1。
不采用KMP算法,在字符串haystack和needle的首位开始循环,当在haystack中匹配到needle第一位时开始逐位判断,若想等返回此时haystack字符串的索引值,若不相等则再从haystack中寻找下一个匹配点,直到到达两字符串size值之差的索引处停止,若没有发现匹配则返回-1。
class Solution {
public:
int strStr(string haystack, string needle) {
int h = haystack.size();
int n = needle.size();
if (n == 0) return 0;
if (h == n&&haystack == needle) return 0;
for (int i = 0; i <= h - n; i++) {
if (haystack[i] == needle[0]) {
bool f = true;
int j = 1;
while (j < n) {
if (haystack[i + j] != needle[j]) {
f = false;
break;
}
j++;
}
if (f) return i;
}
}
return -1;
}
};
编程小白,效率不算高,但是思路十分通俗易懂,写起来也很快,看答案时了解到KMP算法,下篇尝试用KMP算法来实现此题。