資訊讀書會的字串字串
雜湊(哈希)
唬爛(但他是好的
Hash
字典樹啦~
北市賽有考
trie
另一個字串匹配
似乎比較好寫?
Zalgorithm
好的字串匹配
Failure Function
KMP
跟Z很像
專門處理迴文
Manacher
字串的語法小整理
我是一條字串~
我也是喔
I am a string too.
一些字串的語法
#include<iostream>
#include<string>
using namespace std;
int main(){
string a;
cin >> a;
getline(cin, a);
int l=a.length();
a+="abc";
a[1]='e';
string b=a.substr(3, 5);
}
int main(){
string a, b;
cin >> a >> b;
for(int i=0;i<=a.length()-b.length();i++){
bool find=1;
for(int j=0;j<b.length;j++){
if(a[i+j]!=b[j]) find=0;
}
if(find) cout << i << endl;
}
}
等一下會講O(N)
#include <iostream>
#define ll long long
using namespace std;
const ll p=257, M=1e9+7;
ll shash[1000005 ], thash[1000005 ], pp=1, ans=0;
int main(){
string s, t;
cin >> s >> t;
ll n=s.length(), m=t.length();
shash[0]=thash[0]=0;
for(int i=1;i<=n;i++){
shash[i]=(shash[i-1]+pp*s[i-1])%M;
pp=(pp*p)%M;
}
pp=1;
for(int i=1;i<=m;i++){
thash[i]=(thash[i-1]+pp*t[i-1])%M;
pp=(pp*p)%M;
}
pp=1;
for(int i=0;i<=n-m;i++){
if((shash[i+m]-shash[i]+M)%M==thash[m]*pp%M) ans++;
pp=(pp*p)%M;
}
cout << ans << endl;
return 0;
}
tea : 3
ted : 4
in : 5
to : 7
inn : 9
i : 11
ten : 12
A : 15
若\(s[i+1]=s[j]\),則\(\pi [i+1]=j+1\)
否則更新\(j=\pi [j]\)
若\(j=0\),則\(\pi [i+1]=0\),否則重複執行迴圈
#include <iostream>
#include <vector>
using namespace std;
#define ll long long
int main(){
vector<ll> ff;
ll n, m, cnt=0;
string a, b;
cin >> a;
n=a.length();
for(int w=0;w<1;w++){
cin >> b;
m=b.length();
ff.clear();
ff.pb(0);
for(int i=1;i<m;i++){
ff.pb(0);
ll j=i-1;
while(j>=0){
if(b[ff[j]]==b[i]){ff[i]=ff[j]+1;break;}
else j=ff[j]-1;
}
}
ll j=0;
for(int i=0;i<n;i++){
while(a[i]!=b[j] && j>0) j=ff[j-1];
if(j==0 && a[i]!=b[j]) continue;
j++;
if(j==m){
cnt++;
j=ff[j-1];
}
}
}
cout << cnt << endl;
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define ll long long
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);
string s;
cin >> s;
ll n=s.length();
ll z[n], l=0, r=0;
fill(z, z+n, 0);
z[0]=0;
for(int i=1;i<n;i++){
if(i<=r) z[i]=min(r-i+1, z[i-l]);
while(i+z[i]<n && s[z[i]]==s[i+z[i]]) z[i]++;
if(i+z[i]-1>r) l=i, r=i+z[i]-1;
}
for(int i=0;i<n;i++) cout << z[i] << " ";cout << endl;
return 0;
}
\(f_{s}:0,1,0,1,2,1,0,1,0,3,0,1,2,7,2,1,0,1,0,1,0\)
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);
string s, t;
cin >> s;
int n=s.length();
t=".";
for(int i=0;i<n;i++) t+=s[i],t+=".";
n=t.length();
int p[n], mid=-1, r=-1, ans=0;
fill(p, p+n, 0);
for(int i=0;i<n;i++){
if(i<=r) p[i]=min(p[2*mid-i], r-i);
for(int j=p[i]+1;j<=min(i,n-i-1);j++){
if(t[i+j]!=t[i-j]) break;
p[i]++;
}
if(p[i]>p[ans]) ans=i;
if(i+p[i]>r) r=i+p[i], mid=i;
}
for(int i=ans-p[ans]+1;i<=ans+p[ans];i+=2) cout << t[i];cout << endl;
return 0;
}