https://leetcode-cn.com/problems/word-break/

1. 题意

image.png

2. 思路

具体做法是: 弄一个字典树Trie, 然后在Trie中做dfs。
dfs的定义是: dfs(string& s, int index), 表示在字符串s中开始搜索, 当前的搜索区间为 [index, s.size()),看是否能把s这个字符串在trie中搜索完

记忆化: 另外需要用个数组visist记录dfs没搜索到时对应的s中的下标, 用bool或int数组都可以。

为什么做记忆化?
如果不做记忆化, 部分test case会TLE超时, 因为不做记忆化时会有挺多的重复判断。

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. bool visit[310];
  46. bool wordBreak(string s, vector<string>& wordDict) {
  47. Trie trie;
  48. bool flag = false;
  49. for(int i = 0 ; i < 310 ; i ++) {
  50. visit[i] = false;
  51. }
  52. for(string str : wordDict) {
  53. trie.insert(str);
  54. }
  55. function<void(int)> dfs = [&](int index) -> void{
  56. if(index == s.length()) {
  57. flag = true;
  58. return ;
  59. }
  60. if(visit[index]) {
  61. return ;
  62. } else {
  63. visit[index] = true;
  64. }
  65. Trie* p = &trie;
  66. for(int i = index ; i < s.length() ; i ++) {
  67. if(p -> children[s[i] - 'a'] != nullptr) {
  68. p = p -> children[s[i] - 'a'] ;
  69. if(p -> isEnd) {
  70. dfs(i + 1) ;
  71. }
  72. } else {
  73. break;
  74. }
  75. }
  76. };
  77. dfs(0);
  78. return flag;
  79. }
  80. };
  81. int main()
  82. {
  83. // cats an dog cat
  84. string s = "catsandogcat";
  85. vector<string>wordDict{"cats","dog","sand","and","cat","an"};
  86. Solution solution;
  87. int flag = solution.wordBreak(s, wordDict);
  88. cout<< flag << endl;
  89. return 0;
  90. }