745.cc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using std::string;
  5. using std::vector;
  6. using std::cout; using std::endl;
  7. class WordFilter {
  8. public:
  9. WordFilter(vector<string>& words) {
  10. root = new TrieNode();
  11. for (int i = 0; i < words.size(); i++) {
  12. string word = words[i];
  13. int n = word.size();
  14. for (int j = 0; j < n; j++) {
  15. string suffix = word.substr(j, n - j);
  16. insert(suffix + "{" + word, i);
  17. }
  18. }
  19. }
  20. ~WordFilter() {
  21. delete root;
  22. }
  23. int f(string prefix, string suffix) {
  24. return find(suffix + "{" + prefix);
  25. }
  26. private:
  27. class TrieNode {
  28. public:
  29. int index;
  30. bool is_word;
  31. vector<TrieNode*> child;
  32. TrieNode() : index(-1), is_word(false), child(vector<TrieNode*>(27, nullptr)) {}
  33. ~TrieNode() {
  34. for (TrieNode* p : child)
  35. if (p)
  36. delete p;
  37. }
  38. };
  39. TrieNode* root;
  40. void insert(string word, int index) {
  41. TrieNode* node = root;
  42. for (char c : word) {
  43. if (!node->child[c - 'a']) node->child[c - 'a'] = new TrieNode();
  44. node = node->child[c - 'a'];
  45. node->index = std::max(node->index, index);
  46. }
  47. node->is_word = true;
  48. }
  49. int find(string word) {
  50. TrieNode* node = root;
  51. for (char c : word) {
  52. node = node->child[c - 'a'];
  53. if (!node) return -1;
  54. }
  55. return node->index;
  56. }
  57. };
  58. // magic character '{', '{' = 'z' + 1
  59. int main() {
  60. vector<string> words = {"apple", "abble", "epulo"};
  61. WordFilter* wf = new WordFilter(words);
  62. cout << "actual: " << wf->f("a", "e") << ", expected: " << 1 << endl;
  63. cout << "actual: " << wf->f("a", "ple") << ", expected: " << 0 << endl;
  64. cout << "actual: " << wf->f("ep", "pulo") << ", expected: " << 2 << endl;
  65. cout << "actual: " << wf->f("a", "b") << ", expected: " << -1 << endl;
  66. delete wf;
  67. return 0;
  68. }