https://leetcode-cn.com/problems/concatenated-words/

1. 题目

image.png

2. 思路

构建一个字典树,在字典树上进行搜索,要记忆化,不然会超时

3. 题解

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. class Trie {
  4. public:
  5. vector<Trie*>children;
  6. int num;
  7. bool isEnd;
  8. char ch;
  9. Trie* searchPrefix(string prefix){
  10. Trie* node = this;
  11. for(char ch : prefix) {
  12. ch = ch - 'a';
  13. if(node -> children[ch] == nullptr) {
  14. return nullptr;
  15. }
  16. node = node -> children[ch];
  17. }
  18. return node;
  19. }
  20. Trie() : children(26),num(0),isEnd(false){}
  21. void insert(string word) {
  22. Trie* node = this;
  23. for(char ch : word) {
  24. ch -= 'a';
  25. if(node -> children[ch] == nullptr) {
  26. node -> children[ch] = new Trie;
  27. }
  28. node = node -> children[ch];
  29. node -> ch = ch + 'a';
  30. }
  31. node -> num = (node -> num) ++;
  32. node -> isEnd = true;
  33. }
  34. bool search(string word) {
  35. Trie* trie = this -> searchPrefix(word);
  36. return trie == nullptr ? false : trie -> isEnd;
  37. }
  38. bool startsWith(string prefix) {
  39. Trie* trie = this -> searchPrefix(prefix);
  40. return trie == nullptr ? false : true;
  41. }
  42. };
  43. class Solution {
  44. public:
  45. vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
  46. vector<string>vec;
  47. bool visit[10010];
  48. for(int i = 0 ; i < 10010 ; i ++) {
  49. visit[i] = false;
  50. }
  51. Trie trie;
  52. for(string str : words) {
  53. trie.insert(str);
  54. }
  55. bool flag = false;
  56. function<void(string &,int,int)> dfs = [&](string &s,int index,int num) -> void{
  57. if(index == s.length()) {
  58. //判断是否是单词组成的
  59. if(num > 1 ) {
  60. flag =true;
  61. }
  62. return ;
  63. }
  64. if(visit[index]) {
  65. return ;
  66. } else {
  67. visit[index] = true;
  68. }
  69. Trie* p = &trie;
  70. for(int i = index ; i < s.length() ; i ++) {
  71. if(p -> children[s[i] - 'a'] != nullptr) {
  72. p = p -> children[s[i] - 'a'] ;
  73. if(p -> isEnd) {
  74. dfs(s,i + 1,num + 1) ;
  75. }
  76. } else {
  77. break;
  78. }
  79. }
  80. };
  81. for(string str : words) {
  82. memset(visit,0,sizeof(visit));
  83. flag = false;
  84. dfs(str,0,0);
  85. if(flag) {
  86. vec.push_back(str);
  87. }
  88. }
  89. return vec;
  90. }
  91. };
  92. int main()
  93. {
  94. string s = "catsandogcat";
  95. vector<string>wordDict{"cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"};
  96. Solution solution;
  97. vector<string> vec = solution.findAllConcatenatedWordsInADict(wordDict);
  98. for(auto & it : vec) {
  99. cout<< it <<endl;
  100. }
  101. return 0;
  102. }