a ahat hat hatword hziee word
ahat hatword
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
vector<string>m;
char s[50];
int cnt = 1;
struct node
{
int a[26];
int f;
};
node tree[1000*100];
void build_tree()
{
int root = 0;
for(int i = 0; s[i]!= ‘\0‘; i ++)
{
if(tree[root].a[s[i]-‘a‘] == -1)
{
tree[root].a[s[i]-‘a‘] = cnt ++;
}
root = tree[root].a[s[i]-‘a‘] ;
}
tree[root].f = 1;
}
void find_result()
{
int root , root2;
int flag ;
for(int i = 0; i < (int)m.size(); i ++)
{
flag = 0;
//cout << "test==="<<m[i]<<endl;
root = 0;
for(int j = 0; j < (int)m[i].size(); j ++)
{
if(tree[root].a[m[i][j]-‘a‘] != -1)
{
root = tree[root].a[m[i][j]-‘a‘];
if(tree[root].f == 1)
{
//cout << "first paragram=="<<m[i][j]<<endl;
root2 = 0;
int k ;
flag = 0;
for(k = j + 1; k < (int)m[i].size(); k ++)
{
if(tree[root2].a[m[i][k]-‘a‘] == -1)
{
break;
}
root2 = tree[root2].a[m[i][k]-‘a‘];
}
if(k == (int)m[i].size() && tree[root2].f == 1)
{
//cout << "second paragram===" <<m[i][k] <<endl;
printf(m[i].c_str());
printf("\n");
//cout << m[i]<<endl;
flag = 1;
}
}
}
if(flag)break;
}
}
return ;
}
int main()
{
for(int i = 0; i < 1000*100; i ++)
{
tree[i].f = 0;
for(int j = 0; j < 26; j ++)
{
tree[i].a[j] = -1;
}
}
string ss;
int n;
while(scanf("%s",s)!=EOF)
{
ss = s;
n = m.size();
build_tree();
if(n == 0)
{
m.push_back(ss);
}
else if(ss.compare(m[n-1]))
{
m.push_back(ss);
}
}
find_result();
return 0;
}原文:http://blog.csdn.net/mariofei/article/details/22981853