Application of KMP algorithm (27)
We talked about the specific implementation of the KMP algorithm in the last blog, so we will look at the application of the KMP algorithm in this section. Question: how do I find out if a specified substring exists in the target string?
Let's take a look at the new features in the string class, as shown in the following figure
1. Substring lookup (direct application of KMP algorithm)
Int indexOf (const char* s) const
Int indexOf (const String& s) const
Let's look at the implementation of the specific source code, as follows
Int String::indexOf (const char* s) const {return kmp (m_str, s? S: "");} int String::indexOf (const String& s) const {return kmp (m_str, s.m_str);}
We can directly use the kmp function implemented by our blog in the previous section to implement the indexOf function. Let's take a look at the effect.
# include # include # include "DTString.h" using namespace std;using namespace DTLib;int main () {String s = "ababax"; cout