1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| class Solution { public: int strStr(string haystack, string needle) { int m = haystack.size(), i = 0; int n = needle.size(), j = 0; if (needle.empty()) { return 0; }else if(haystack.empty()|| m<n){ return -1; } size_t length = needle.size(), fast = 0; int *next = new int[length]; int slow = next[0] = -1; while (fast < length-1) { if ((0 > slow || needle[fast] == needle[slow])) { fast++; slow++; next[fast] = slow; } else { slow = next[slow]; } } int flag = 0; while (j < n && i < m) { if (0 > j || haystack[i] == needle[j]) { i++; j++; if(needle[j]=='\0'){ flag = 1;break; } } else { j = next[j]; } } delete[] next; if (flag) return i-j; return -1; } };
int match (char* P, char* S){ int* next = buildNext(P); int m = (int) strlen (S), i = 0; int n = (int) strlen(P), j = 0; while (j < n && i < m) if (0 > j || S[i] == P[j]) {i++; j++;} else j = next[j]; delete [] next; return i - j; }
int* buildNext(char* P) { size_t m = strlen(P), j = 0; int* N = new int[m]; int t = N[0] = -1; while (j < m - 1) if ( 0 > t || P[j] == P[t]){ j++; t++; N[j] = t; }else t = N[t]; return N;
}
|