题意: 给出一本字典, 和一篇文章,根据字典翻译文章,若字典里面没有文章中的某个单词,则不用翻译
解法:两种解法: 1. 用c++ 的stl里面的map来求解, 直接把每个单词用map对应即可
2. 根据生词表建立字典树, 直接在字典树里面查询即可, 下面简要介绍一下字典树:
字典树: 以英文小写字母为例: 一个字典树有一个根节点:root, 根节点下面有26个节点,分别对应a~z ,此后,从根节点往下,每个节点下面均有26个节点即a~z, 这样,一个单词,如 love, 顺着根节点往下,依次是:next[11], next[14], next[21], next[4], 则一共经历了4层,这样查询时间复杂度仅为o(len), (len为单词长度)。这里给出动态分配内存的字典树代码,根据代码很好写出静态分配内存的代码:
CODE of c++ stl map: 1546ms
#include <map>
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
map<string, string> dic;
int main()
{
// freopen("/Users/apple/Desktop/in.txt", "r", stdin);
string word1, word2, word;
cin >> word;
while (cin >> word1 && word1 != "END")
{
cin >> word2;
dic[word2] = word1;
}
cin >> word;
getchar();
while (getline(cin, word) && word != "END")
{
word1 = "";
for (int i = 0; i < word.size(); i++) {
if (word[i] >= 'a' && word[i] <= 'z') {
word1 += word[i];
}
else {
if (dic.find(word1) == dic.end()) cout << word1;
else cout << dic[word1];
cout << word[i];
word1 = "";
}
}
printf("\n");
}
return 0;
}
CODE of Tree Tree: 578ms
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
const int maxn = 26;
typedef string Type;
struct Tree {
Type s;
Tree* next[maxn];
};
typedef Tree* pTree;
pTree root;
void init()
{
root = new Tree;
for (int i = 0; i < maxn; i++) {
root->next[i] = NULL;
}
root->s = "";
}
void insert(string a, string b)
{
pTree p = root, q;
for (int i = 0; i < a.size(); i++) {
int id = a[i] - 'a';
if (p->next[id] == NULL) {
q = new Tree;
q->s[0] = 0;
for (int j = 0; j < maxn; j++) {
q->next[j] = NULL;
}
p->next[id] = q;
}
p = p->next[id];
}
p->s = b;
}
string find(string a)
{
pTree p = root;
for (int i = 0; i < a.size(); i++) {
int id = a[i] - 'a';
if (p->next[id] == NULL) {
return a;
}
p = p->next[id];
}
if (p->s[0]) {
return p->s;
}
return a;
}
void clear(pTree u)
{
for (int i = 0; i < maxn; i++) {
if (u->next[i]) {
clear(u->next[i]);
}
}
free(u);
}
int main()
{
init();
// freopen("/Users/apple/Desktop/in.txt", "r", stdin);
string word1, word2, word;
cin >> word;
while (cin >> word1 && word1 != "END")
{
cin >> word2;
insert(word2, word1);
}
cin >> word;
getchar();
while (getline(cin, word) && word != "END")
{
word1 = "";
for (int i = 0; i < word.size(); i++) {
if (word[i] >= 'a' && word[i] <= 'z') {
word1 += word[i];
}
else {
cout << find(word1);
cout << word[i];
word1 = "";
}
}
printf("\n");
}
clear(root);
return 0;
}