今日头条,双生词
今日头条,双生词,虽然没有过,还是写一下我的思路,请各位指教一下
第一种方法是用hash的方法做,过60%,后面就超时了
第二种方法是用trie树做,提交的时候没有考虑长度不相等的情况,考试结束才发现,不知道改过之后的代码能不能过
下面贴一下两种思路的代码。
#include "iostream"
#include "string"
#include "unordered_set"
#include "algorithm"
using namespace std;
int main(int, char*[]) {
int t, n;
while(cin >> t) {
while(t--) {
cin >> n;
bool res = false;
string str, dou, tmp;
unordered_set<string> set;
while(n--) {
cin >> str;
dou = str + str;
for(int i = 0, len = str.size(); i < len; i++) {
tmp = dou.substr(i, len);
if(set.find(tmp) != set.end())
res = true;
reverse(tmp.begin(), tmp.end());
if(set.find(tmp) != set.end())
res = true;
}
set.insert(str);
}
cout << (res ? "Yeah" : "Sad") << endl;
}
}
}
#include "iostream"
#include "string"
#include "vector"
#include "algorithm"
using namespace std;
class Node {
public:
Node *next[26];
Node() {
for(int i = 0; i < 26; i++)
next[i] = nullptr;
}
};
bool rechk(Node *root, string &str, int i) {
if(i >= str.size() && root == nullptr)
return true;
int ind = str[i] - 'a';
if(root->next[ind] == nullptr)
return false;
return rechk(root->next[ind], str, i+1);
}
bool check(Node *root, string &str) {
string dou = str + str;
string tmp;
for(int i = 0, len = str.size(); i < len; i++) {
tmp = dou.substr(i, len);
if(rechk(root, tmp, 0))
return true;
reverse(tmp.begin(), tmp.end());
if(rechk(root, tmp, 0))
return true;
}
return false;
}
Node* add(Node *root, string &str, int i) {
if(root == nullptr)
root = new Node();
if(i >= str.size())
return root;
int ind = str[i] - 'a';
root->next[ind] = add(root->next[ind], str, i+1);
return root;
}
int main(int, char*[]) {
int t, n;
while(cin >> t) {
while(t--) {
cin >> n;
bool res = false;
string str;
Node *root = new Node();
while(n--) {
cin >> str;
if(check(root, str))
res = true;
add(root, str, 0);
}
cout << (res ? "Yeah" : "Sad") << endl;
}
}
return 0;
}#字节跳动##笔试题目#
查看8道真题和解析