28. Implement strStr()
Posted ruruozhenhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了28. Implement strStr()相关的知识,希望对你有一定的参考价值。
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C‘s strstr() and Java‘s indexOf().
AC code:
this code is low effective.
class Solution { public: int strStr(string haystack, string needle) { int len1 = haystack.length(); int len2 = needle.length(); if (len2 == 0) { return 0; } for (int i = 0; i < len1; ++i) { int index = i; int j = 0; while (haystack[index] == needle[j] && index < len1 && j < len2) { index++; j++; } if (j == len2) { return i; } } return -1; } };
Runtime: 812 ms, faster than 3.41% of C++ online submissions for Implement strStr().
Only have a little change, but the effective have a big exaltation.
class Solution { public: int strStr(string haystack, string needle) { int len1 = haystack.length(); int len2 = needle.length(); if (len2 == 0) { return 0; }
// i < len1 - len2 for (int i = 0; i < len1-len2+1; ++i) { int index = i; int j = 0; while (haystack[index] == needle[j] && index < len1 && j < len2) { index++; j++; } if (j == len2) { return i; } } return -1; } };
Runtime: 8 ms, faster than 37.69% of C++ online submissions for Implement strStr().
But this way is a brute-force algorithm, too. may be this question want you to use brute-force.
The high effective algorithm is to use KMP algorithm.
class Solution { public: int strStr(string haystack, string needle) { int m = haystack.length(), n = needle.length(); if (!n) { return 0; } vector<int> lps = kmpProcess(needle); for (int i = 0, j = 0; i < m; ) { if (haystack[i] == needle[j]) { i++; j++; } if (j == n) { return i - j; } if ((i < m) && (haystack[i] != needle[j])) { if (j) { j = lps[j - 1]; } else { i++; } } } return -1; } private: vector<int> kmpProcess(string& needle) { int n = needle.length(); vector<int> lps(n, 0); for (int i = 1, len = 0; i < n; ) { if (needle[i] == needle[len]) { lps[i++] = ++len; } else if (len) { len = lps[len - 1]; } else { lps[i++] = 0; } } return lps; } };
Runtime: 8 ms, faster than 37.69% of C++ online submissions for Implement strStr().
以上是关于28. Implement strStr()的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 28. Implement strStr() 实现strStr()