【字符串】实现strStr()
题目描述:
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
示例:
输入: haystack = “hello”, needle = “ll”
输出: 2输入: haystack = “aaa”, needle = “aaaaaa”
输出: -1
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.length() == 0){
return -1;
}
for(int i=0; i<=haystack.length() - needle.length(); i++){
bool flag = true;
for(int j=0; j<needle.length(); j++){
if(haystack[i+j] != needle[j]){
flag = false;
break;
}
}
if(flag){
return i;
}
}
return -1;
}
};
int main()
{
string str1 = "ab";
string str2 = "ab";
Solution solution;
int result = solution.strStr(str1, str2);
cout << result << endl;
return 0;
}
方法二、KMP算法
class Solution {
public:
void getNext(int* next, const string& s) {
int j = -1;
next[0] = j;
for(int i = 1; i < s.size(); i++) { // 注意i从1开始
while (j >= 0 && s[i] != s[j + 1]) { // 前后缀不相同了
j = next[j]; // 向前回溯
}
if (s[i] == s[j + 1]) { // 找到相同的前后缀
j++;
}
next[i] = j; // 将j(前缀的长度)赋给next[i]
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
int next[needle.size()];
getNext(next, needle);
int j = -1; // // 因为next数组里记录的起始位置为-1
for (int i = 0; i < haystack.size(); i++) { // 注意i就从0开始
while(j >= 0 && haystack[i] != needle[j + 1]) { // 不匹配
j = next[j]; // j 寻找之前匹配的位置
}
if (haystack[i] == needle[j + 1]) { // 匹配,j和i同时向后移动
j++; // i的增加在for循环里
}
if (j == (needle.size() - 1) ) { // 文本串s里出现了模式串t
return (i - needle.size() + 1);
}
}
return -1;
}
};