题目链接:
题意:
给你很多字符串,问如果其中某个字符串可以由其他两个已经给你的字符串拼接而成,就输出这个字符串;
分析:
好像可以用map;这里用的是字典树,把所有的字符串存入字典树,并将字符串结尾的字符编号都标记上(因为如果一个字符串s,可以由a和b拼接而成,假设a是s的前缀,那么你查询的时候,就应该把含有前缀为a的字符串的这种查询给去除掉),然后对于每个字符串进行判断,枚举截断的位置,两边进行查询,如果都存在,则输出,然后break进入下个字符串的判断;
C++String的类及一些函数:https://www.cnblogs.com/X-Do-Better/p/8628492.html
代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
#include<map>
using namespace std;
const int inf=0x7f7f7f7f;
const int maxn=1e5+50;
const int N=50;
typedef long long ll;
typedef struct{
ll u,v,next,w;
}Edge;
Edge e[N];
int cnt,head[N];
inline void add(int u,int v){
e[cnt].u=u;
e[cnt].v=v;
//e[cnt].w=w;
// e[cnt].f=f;
e[cnt].next=head[u];
head[u]=cnt++;
// e[cnt].u=v;
// e[cnt].v=u;
// e[cnt].w=0;
// e[cnt].f=-f;
// e[cnt].next=head[v];
// head[v]=cnt++;
}
inline int read()
{
int x = 0;
int f = 1;
char c = getchar();
while (c<'0' || c>'9')
{
if (c == '-')
f = -1;
c = getchar();
}
while (c >= '0'&&c <= '9')
{
x = x * 10 + c - '0';
c = getchar();
}
return x*f;
}
int tol=1,l,r,cnt1,trie[maxn][30],mark[maxn];
string st[maxn];
void insert(string s){
int p=1;
for(int i=0;i<s.length();i++){
int ch=s[i]-'a';
if(!trie[p][ch])trie[p][ch]=++tol;
p=trie[p][ch];
}
mark[p]=1;
}
bool query(string s){
int p=1;
for(int i=0;i<s.length();i++){
int ch=s[i]-'a';
if(!trie[p][ch])return 0;
p=trie[p][ch];
}
return mark[p];//如果p是一个字符串的结尾字符编号,则返回true,否则返回false
}
int main() {
string s;
while(cin>>s){
insert(s);
st[cnt1++]=s;
}
for(int i=0;i<cnt1;i++)
for(int j=1;j<st[i].length();j++){
string s1(st[i],0,j);
string s2(st[i],j);
/*cout<<st[i]<<" "<<s1<<" "<<s2<<endl;
cout<<query(s1)<<endl;
cout<<query(s2)<<endl;*/
if(query(s1)&&query(s2)){
cout<<st[i]<<endl;
break;
}
}
}
(仅供个人理解)