題意: 給出一本字典, 和一篇文章,根據字典翻譯文章,若字典裏面沒有文章中的某個單詞,則不用翻譯
解法:兩種解法: 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;
}