题意
有一些电话号码,如果这些电话号码没有重复前缀则输出No,有重复的前缀则输出Yes
版本2
使用Trie树
注意需要先把短的电话号码先插入。
比如
2
111
1
正确结果应该输出有重复
如果不排序的话,会出错。
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <unordered_map>
using namespace std;
bool res;
struct Node{
bool end;
Node* son[26];
Node(){
end = false;
for(int i = 0; i < 26; i++) son[i] = nullptr;
}
};
void Insert(string &word, Node* p){ //按照建树的方式来建Trie树
for(auto c: word){
int u = c - '0';
if(p->son[u] == nullptr) p->son[u] = new Node();
p = p->son[u];
if(p->end) res = true;
}
p->end = true;
}
int main(){
int n;
string str;
while(cin>>n){
res = false;
Node *root = new Node();
vector<string> vt;
while(n--){
cin>>str;
vt.push_back(str);
}
sort(vt.begin(), vt.end());
for(auto s: vt)
Insert(s, root);
if(!res) cout<<"No"<<endl;
else cout<<"Yes"<<endl;
}
return 0;
}
版本1
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <unordered_map>
using namespace std;
bool res;
int main(){
int n;
string str;
while(cin>>n){
res = false;
vector<string> vt;
while(n--){
cin>>str;
vt.push_back(str);
}
sort(vt.begin(), vt.end());
for(int i = 1; i < vt.size(); i++)
if(vt[i].find(vt[i-1]) != string::npos){
res = true;
break;
}
if(!res) cout<<"No"<<endl;
else cout<<"Yes"<<endl;
}
return 0;
}

本文介绍了一种用于检查电话号码是否具有重复前缀的算法。通过两种方法实现:一种是基于字符串查找的方法,另一种是使用Trie树进行优化。文章详细解释了为何需要先对电话号码进行排序,并提供了完整的C++代码实现。
880

被折叠的 条评论
为什么被折叠?



