#include "iostream"
#define MAXSIZE 100
using namespace std;
int getIndexOf(string str1, string str2);
int *getNextArr(string str);
int main() {
string str = "abdes";
string t = "de";
cout << getIndexOf(str, t);
}
int getIndexOf(string str1, string str2) {
if (str1.empty() || str2.empty() || str2.length() < 1 || str1.length() < str2.length()) {
return -1;
}
int x = 0;
int y = 0;
int *next = getNextArr(str2);
while (x < str1.length() && y < str2.length()) {
if (str1[x] == str2[y]) {
++x;
++y;
} else if (next[y] == -1) {
++x;
} else {
y = next[y];
}
}
return y == str2.length() ? x - y : -1;
}
int *getNextArr(string str) {
if (str.length() == 1) {
return new int[1]{-1};
}
int *next = new int[str.length()];
next[0] = -1;
next[1] = 0;
int i = 2;
int currentNumber = 0;
while (i < str.length()) {
if (str[i - 1] == str[currentNumber]) {
next[i++] = ++currentNumber;
} else if (currentNumber > 0) {
currentNumber = next[currentNumber];
} else {
next[i++] = 0;
}
}
return next;
}
|