Advertisement
Guest User

Untitled

a guest
Oct 25th, 2014
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <vector>
  3. #include <string>
  4. #include <set>
  5. #include <iostream>
  6. #include <stdlib.h>
  7.  
  8. using namespace std;
  9.  
  10. #define MAX_WORD_SZ 20 // max length of a word
  11.  
  12. set<string> dict; // words I can use
  13.  
  14. void initialize_dict(){
  15. dict.insert("how");
  16. dict.insert("are");
  17. dict.insert("you");
  18. dict.insert("h");
  19. dict.insert("o");
  20. dict.insert("w");
  21. }
  22.  
  23. // "inseartSpaces" in stream starting at position start
  24. vector<vector<string>> insertSpaces(string stream, int start){
  25. int l = stream.length();
  26. vector<vector<string>> result;
  27. result.clear(); // make sure result is empty
  28.  
  29. // find word at beginning of stream
  30. string word = "";
  31. for(int i=start; i<l && i<MAX_WORD_SZ ; ++i){
  32. word += stream[i];
  33.  
  34. if( dict.find(word) != dict.end() ){
  35. vector<vector<string>> aux = insertSpaces(stream, i+1);
  36. if( i+1 == l ){
  37. vector<string> wl;
  38. wl.push_back(word);
  39. result.push_back(wl);
  40. //return result; // result is a list of one list with a word in it
  41. }
  42. else if( aux.size() != 0 ){
  43. int sz = aux.size();
  44. vector<string> wl;
  45. for(int j=0; j<sz; ++j ){
  46. wl.clear();
  47. wl.push_back(word);
  48. wl.insert(wl.end(), aux[j].begin(), aux[j].end());
  49. result.push_back(wl);
  50. }
  51. }
  52.  
  53. }
  54. }
  55.  
  56. return result; // will be empty list
  57. }
  58.  
  59. void solve_recursive(string stream){
  60. printf("Recursive solution:\n");
  61. vector<vector<string>> result;
  62. result = insertSpaces(stream, 0);
  63.  
  64. for(auto it=result.begin(); it!=result.end(); ++it){
  65. for(auto it2=it->begin(); it2!=it->end(); ++it2)
  66. cout << *it2 << " ";
  67. cout << "\n";
  68. }
  69.  
  70. cout<< "\n";
  71. }
  72.  
  73. int main(){
  74. initialize_dict();
  75.  
  76. solve_recursive("howareyou");
  77. solve_recursive("how");
  78. solve_recursive("ho");
  79. //solve_iterative(inputString);
  80.  
  81. return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement