//运行时间:8ms class Solution { public: int strStr(string haystack, string needle) { if (needle.empty()) return 0; int h_len = haystack.length(); int n_len = needle.length(); if (h_len < n_len) return -1; //int ans = haystack.find(needle, 0); //if (ans == string::npos) return -1; //return ans; int i = 0; int m = 0; int j = 0; bool flag = false; int ans; while (i < h_len){ ans = i - m; j = m; m = 0; while (i < h_len&&j < n_len&&haystack[i] == needle[j]){ if (j){ if (needle[j] == needle[m]) m++; else m = 0; } i++; j++; } if (j == n_len) { flag = true; break; } if (!j) i++; } if (flag) return ans; return -1; } };
leetcode028:Implement strStr()
原文地址:http://blog.csdn.net/barry283049/article/details/45092765