题解 P3966 【[TJOI2013]单词】

· · 题解

这道题可以用字符串的find做,虽然代码易打,但还是有要注意的地方:

1:每次查找位置以后,下一次查找的位置是以上一次查找的位置加1,否则就会死循环。

2:当find查找不到的时候,似乎会返回一个很大的值,所以,查找的位置小于字符串长度即可。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,ans;
string s[210];
int main() {
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);//一个优化
    cin>>n;
    for(register int i=1; i<=n; ++i) cin>>s[i];
    for(register int i=1; i<=n; ++i) {
        ans=0;
        for(register int j=1; j<=n; ++j) {
            int k=0,kk=s[j].find(s[i],k);
            while(kk<s[j].length()) {
                k=kk+1;
                kk=s[j].find(s[i],k);
                ++ans;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}