leetcode_c++:Implement strStr() (028)
2016-08-05 19:42
495 查看
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
//在一个字符串中找到另一个字符串在其中的位置
//KMP
O(n)
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
//在一个字符串中找到另一个字符串在其中的位置
//KMP
O(n)
class Solution { public: int strStr(string haystack, string needle) { return strStrKMP(haystack, needle); } private: // KMP int strStrKMP(string haystack, string needle) { if (needle.empty()){ return 0; } int i = 0; int hSize = static_cast<int>(haystack.size()); int nSize = static_cast<int>(needle.size()); if (hSize < nSize){ return -1; } vector<int> next(nSize, -1); calcNext(needle, next); int j = 0; while (i < hSize) { if (j == -1 || haystack[i] == needle[j]){ i++; j++; }else{ j = next[j]; } if (j >= nSize){ return i - nSize; } } return -1; } void calcNext(const string& needle, vector<int> &next){ int nSize = static_cast<int>(needle.size()); int i = 0; int j = -1; while (i < nSize - 1) { if (j == -1 || needle[i] == needle[j]){ i++; j++; next[i] = j; }else{ j = next[j]; } } } };
相关文章推荐
- [LeetCode] 028. Implement strStr() (Easy) (C++/Python)
- LeetCode 028 Implement strStr()
- C++ 写leetcode遇到的一些问题总结Implement strStr()
- LeetCode刷题(C++)——Implement strStr()(Easy)
- LeetCode-028 Implement strStr()
- LeetCode 28 — Implement strStr()(C++ Java Python)
- Java for LeetCode 028 Implement strStr()
- 【leetcode c++】28 Implement strStr()
- LeetCode 028 Implement strStr()
- 2017-09-17 LeetCode_028 Implement strStr()
- leetcode 28 Implement strStr() C++
- [C++]LeetCode 28: Implement strStr() (实现strStr()函数)
- LeetCode 028 Implement strStr()
- [C++]LeetCode: 27 Implement strStr()
- 【LeetCode】 028. Implement strStr()
- 【LeetCode-面试算法经典-Java实现】【028-Implement strStr() (实现strStr()函数)】
- 【LeetCode】028.Implement strStr()
- LeetCode 028. Implement strStr()
- [LeetCode]题解(python):028-Implement strStr()
- LeetCode: Implement strStr()