数据结构之串
串(string)是由零个或多个字符组成的优先序列。 串同样有顺序和链式两种存储结构,在顺序存储结构中,通常用’ \0 '来表示串值的终结。串的概念很easy,这里主要记一下串的KMP模式匹配算法。
这个视频讲KMP算法讲的非常好:
https://www.bilibili.com/video/av47471886?from=search&seid=1662715013483300410
具体的算法过程都在视频里了,其实看算法是基础,最重要的还是自己写一遍,这样才能理解算法的精髓:
#include <iostream>
#include <vector>
using namespace std;
void get_nextval(string t, vector <int> &nextval)
{
int i = 1, j = 0;
nextval.push_back(0);
while(i < t.length())
{
if(j == 0|| t[i] == t[j])
{
i++;
j++;
if(t[i] != t[j]) nextval.push_back(j);
else nextval.push_back(nextval[j]);
}
else
{
j = nextval[j] - 1;
}
}
}
int Index_kmp(string s, string t,vector <int> next)
{
int i = 0, j = 1;
while(i < s.length() && j <= t.length())
{
if(s[i] == t[j - 1] || j == 0)
{
++i;
++j;
}
else(j = next[j - 1]);
}
if(j >= t.length())
return i - t.length();
return 0;
}
int main()
{
string s,ssub;
vector<int> next;
cin >> s;
cin >> ssub;
get_nextval(ssub, next);
cout << Index_kmp(s, ssub, next) << endl;
return 0;
}
串是很常用也很实用的一种数据结构,Leetcode上有很多串的经典题目,例如最长回文子串,无重复字符的最长子串等等。