1. 题意

image.png

2. 思路

构建一个Trie树,然后进行搜索

3. 题解

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. class TrieNode{
  4. public:
  5. vector<TrieNode*> child;
  6. bool isWord;
  7. TrieNode() : child(26, nullptr), isWord(false) {};
  8. ~TrieNode() {
  9. for (auto c : child) delete c;
  10. }
  11. };
  12. class WordDictionary {
  13. private:
  14. TrieNode* root;
  15. public:
  16. /** Initialize your data structure here. */
  17. WordDictionary() {
  18. root = new TrieNode();
  19. }
  20. ~WordDictionary() {
  21. delete root;
  22. }
  23. /** Adds a word into the data structure. */
  24. void addWord(string word) {
  25. TrieNode* p = root;
  26. for (char c : word) {
  27. int i = c - 'a';
  28. if (!p->child[i])
  29. p->child[i] = new TrieNode();
  30. p = p->child[i];
  31. }
  32. p->isWord = true;
  33. }
  34. /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
  35. bool search(string word) {
  36. return match(word, root, 0);
  37. }
  38. bool match(string& word, TrieNode* p, int start) {
  39. if (!p) return false;
  40. if (start == word.size()) return p->isWord;
  41. char c = word[start];
  42. if (c != '.') {
  43. return match(word, p->child[c - 'a'], start + 1);
  44. } else {
  45. for (const auto& child : p->child) {
  46. if (match(word, child, start + 1))
  47. return true;
  48. }
  49. }
  50. return false;
  51. }
  52. };
  53. int main()
  54. {
  55. return 0;
  56. }