POJ 1035 Spell checker
2010-11-19 17:08
288 查看
解题思路:trie树+排序,理论上效率应该不错,不过可能由于new过于平凡,效率不是很高,还不如长度排序之后直接搜索
完整代码如下:
代码
完整代码如下:
代码
#include <iostream> #include <map> using namespace std; struct dictree { dictree *child[26]; dictree *father; char ch; bool isEnd; int index; }; dictree *root = new dictree(); struct node { char word[16]; }; map<int, node> ans; map<int, node>::iterator iter; void insert(dictree *leaf) { int index, L = 0; char str[16]; node temp; index = leaf->index; while (leaf != root) { str[L++] = leaf->ch; leaf = leaf->father; } for(int i = 0; i < L; i++) temp.word[i] = str[L - 1 - i]; temp.word[L] = '\0'; ans[index] = temp; } dictree* Find( dictree *root, char *word) { dictree *cur = root, *next; for (int i = 0; (i < strlen(word)) && cur; i++) { next = cur->child[word[i] - 'a']; cur = next; } if (cur && cur->isEnd)return cur; return NULL; } int main() { char word[16]; dictree *leaf, *cur, *next; int len = 0; while (cin.getline(word, 16) && word[0] != '#') { cur = root; for (int i = 0; i < strlen(word); i++,cur = next) { next = cur->child[word[i] - 'a']; if (next == NULL) { next = new dictree(); next->ch = word[i]; cur->child[word[i] - 'a'] = next; next->father = cur; } if (i == strlen(word) - 1) { next->index = len++; next->isEnd = true; } } } while (cin.getline(word, 16) && word[0]!= '#') { if (Find(root, word)) { printf("%s is correct\n", word); continue; } cur = root; for (int i = 0; (i < strlen(word)) && cur; i++) { for (int j = 0; j < 26; j++) { if (j == word[i] - 'a') continue; if (leaf = Find(cur->child[j], &word[i])) insert(leaf); if (word[i + 1] == '\0') { if (cur->isEnd) insert(cur); if (cur->child[j] && cur->child[j]->isEnd) insert(cur->child[j]); } if (leaf = Find(cur->child[j], &word[i + 1])) insert(leaf); if (leaf = Find(cur, &word[i + 1])) insert(leaf); } cur = cur->child[word[i] - 'a']; } if (cur) for (int i = 0; i < 26; i++) if (cur->child[i] && cur->child[i]->isEnd) insert(cur->child[i]); printf("%s:", word); for (iter = ans.begin(); iter != ans.end(); iter++) printf(" %s", (iter->second).word); printf("\n"); ans.clear(); } return 0; }
相关文章推荐
- poj1035 Spell checker
- poj 1035 -- Spell checker
- poj1035_Spell checker
- POJ 1035 Spell checker
- POJ 1035 Spell checker
- POJ 1035 Spell checker
- POJ1035——Spell checker
- poj1035 Spell checker
- POJ1035——spell checker
- Poj 1035 --Spell checker
- POJ 1035 Spell checker
- poj 1035 Spell checker
- POJ 1035 Spell checker
- poj 1035 Spell checker
- poj-1035-Spell checker
- poj1035 Spell checker
- poj1035——Spell checker
- poj 1035 Spell checker
- poj1035 Spell checker
- POJ 1035 Spell checker