方法一:字典树
515ms
#include<iostream> #include<string> using namespace std; struct Trie { string s; //在每个单词的末尾节点上保存该单词的英语意思 Trie *next[26]; Trie() { s = ""; memset(next,0,sizeof(next)); } }; void Insert(Trie *root,string s1,string s2) { Trie *p = root; for(int i = 0; i < s2.size(); i++) { int j = s2[i] - 'a'; if(p->next[j] == NULL) p->next[j] = new Trie(); p = p->next[j]; } p->s = s1; } void Find(Trie *root,string s) { Trie *p = root; for(int i = 0; i < s.size(); i++) { int j = s[i] - 'a'; if(p->next[j] == NULL) { cout << s; return; } p = p->next[j]; } if(p->s == "") cout << s; else cout << p->s; } int main() { //freopen("1004.txt","r",stdin); string s,s1,s2; Trie *root = new Trie(); cin >> s; while(cin >> s1 && s1 != "END") { cin >> s2; Insert(root,s1,s2); } cin >> s; getchar(); //读取换行符 while(getline(cin,s) && s != "END") { int i,j = 0; for(i = 0; i < s.size(); i++) { if(s[i] < 'a' || s[i] > 'z') { s1 = s.substr(j,i-j); //把s中从下标i开始长度为i-j的子串赋给s1 Find(root,s1); cout << s[i]; j = i+1; } } cout << endl; } return 0; }
方法二: stl中的map
1562ms
#include<iostream> #include<map> #include<string> using namespace std; int main() { freopen("1004.txt","r",stdin); char c[100]; map<string,string> m; map<string,string>::iterator it; string s,s1,s2; cin >> s; while(cin >> s1 && s1 != "END") { cin >> s2; m[s2] = s1; } cin >> s; getchar(); while(getline(cin,s) && s != "END") { int j = 0; for(int i = 0; i < s.size(); i++) { if(s[i] < 'a' || s[i] > 'z') { s1 = s.substr(j,i-j); it = m.find(s1); if(it != m.end()) cout << m[s1]; else cout << s1; cout << s[i]; j = i+1; } } cout << endl; } return 0; }