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

1. 题意

image.png

2. 思路

构建一个trie树,然后在树上搜索单词,搜索成功就记下来

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. vector<string> wordBreak(string s, vector<string>& wordDict) {
  47. Trie trie;
  48. vector<string> vec;
  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,string)> dfs = [&](int index,string str) -> void{
  56. if(index == s.length()) {
  57. vec.push_back(str);
  58. }
  59. Trie* p = &trie;
  60. string temp;
  61. for(int i = index ; i < s.length() ; i ++) {
  62. if(p -> children[s[i] - 'a'] != nullptr) {
  63. p = p -> children[s[i] - 'a'] ;
  64. temp.push_back(s[i]);
  65. if(p -> isEnd) {
  66. if(str.size() != 0 && str.substr(str.size() -1) != " ") {
  67. //注意这里有肯能多加空格,要判断一下加过空格不用在添加
  68. str += " ";
  69. }
  70. dfs(i + 1,str + temp) ;
  71. }
  72. } else {
  73. break;
  74. }
  75. }
  76. };
  77. dfs(0,"");
  78. return vec;
  79. }
  80. };
  81. int main()
  82. {
  83. //此例子如狗不多加空格判断会,会出现错误
  84. string s = "pineapplepenapple";
  85. vector<string>wordDict{"apple","pen","applepen","pine","pineapple"};
  86. Solution solution;
  87. vector<string> vec = solution.wordBreak(s,wordDict);
  88. for(auto it : vec) {
  89. cout<< it <<endl;
  90. }
  91. return 0;
  92. }