版权声明:未经允许禁止转载。转载请联系我WX:yuyi5453。并且注明出处 https://blog.csdn.net/weixin_40532377/article/details/83003750
题目链接:http://poj.org/problem?id=2001
题目大意:给你了一堆字符串,然后问你不和其他字符串前缀相同的最短前缀是什么。
比如你给的:carton和carbon 就应该输出cart和carb 因为car是相同的前缀。
题目思路:创建一棵字典树,节点记录每个字符出现的次数,当search到只出现过1次的字母时,那么这个
前缀就是独一无二的。
但是!!请求大佬帮我看一下我代码,我觉得没什么问题,而且去网上看了AC的代码,和我的思路几乎
一样,而且我也对照了代码,细节处理也都一样,但是就是WA。
(——更新于20分钟之后——)
突然脑子灵光一闪,有了点思路,好像知道哪里错了。
search函数最后那条语句。当一个字符串整个串都是和其他字符串的前缀,那么就输出这个
字符串,从break出来的是没错了,输出0~i的字符,但是当*q==‘\0’,出来时就会错误。
比如说,car 应该输出第0~2个字符,但是又没没有break , i变成3了,第三个位置上是'\0',
但是什么也输不出来(你自己看不到),所以你看到的答案和样例是一样的,但是测评姬是
可以看到的。
所以说,细节是很重要的。至于怎么灵光一闪的。。。我也说不清。多找,多问,多看吧。
另外,POJ上用C++提交,G++给我报了RE,我也不知道为啥。还有就是POJ上不能直接写
#include<bits/stdc++.h>
代码:
#include<iostream>
#include<queue>
#include<cstring>
#include<stdlib.h>
using namespace std;
const int maxn=26;
struct Trie{
int cnt; //记录出现几次
Trie *next[maxn];
};
Trie* init(Trie* p){
p=new Trie; //p=(Trie*)malloc(sizeof(Trie))
p->cnt=0;
for(int i=0;i<maxn;i++){
p->next[i]=NULL;
}
return p;
}
void insert(Trie *root,char* s){
if(root==NULL||*s=='\0'){
return ;
}
Trie *p=root;
char* q=s;
while(*q!='\0'){
if(!p->next[*q-'a']){
Trie* temp=init(temp);
p->next[*q-'a']=temp;
}
p=p->next[*q-'a'];
p->cnt++;
q++;
}
}
int i;
void search(Trie *root,char *s){
Trie* p=root;
char* q=s;
i=0;
while(p->next[*q-'a']&&*q!='\0'){
p=p->next[*q-'a'];
if(p->cnt==1) break;
i++;
q++;
}
if(*q=='\0') i--; //这个新增之后就AC的一条语句
}
int main()
{
Trie* root=init(root);
queue<char*>st;
char* s=(char*)malloc(25*sizeof(char));
while(~scanf("%s",s)){
st.push(s);
insert(root,s);
s=(char*)malloc(25*sizeof(char));
}
char* ss=(char*)malloc(25*sizeof(char));
while(!st.empty()){
ss=st.front();
printf("%s ",ss);
search(root,ss);
for(int k=0;k<=i;k++)
printf("%c",*(ss+k));
cout<<endl;
st.pop();
}
}