Fastrail08

Word Break

May 10th, 2025 (edited)
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. // added a level parameter to see the prefix at each level and their recursive calls
  6. void wordBreak(string word, vector<string> &pathString, unordered_set<string> &dictionary, int level){
  7.     if(word.size() == 0){
  8.         for(string s : pathString){
  9.             cout << s << " ";
  10.         }
  11.         cout << '\n';
  12.         return;
  13.     }
  14.     //create different prefix and see if it is a valid word in dictionary
  15.     for(int i = 1; i <= word.size(); i++){
  16.         string prefix = word.substr(0, i);
  17.         if(dictionary.count(prefix)){
  18.             pathString.push_back(prefix);
  19.             string ros = word.substr(i);
  20.             // cout << prefix << " " << level << '\n';
  21.             wordBreak(ros, pathString, dictionary, level + 1);
  22.             pathString.pop_back();
  23.         }
  24.     }
  25. }
  26.  
  27. int main() {
  28.     // your code goes here
  29.     int n;
  30.     cin >> n;
  31.     string word;
  32.     unordered_set<string> dictionary;
  33.     for(int i = 0; i < n; i++){
  34.         string s;
  35.         cin >> s;
  36.         dictionary.insert(s);
  37.     }
  38.     cin >> word;
  39.     vector<string> pathString;
  40.     wordBreak(word, pathString, dictionary, 0);
  41. }
  42.  
  43.  
  44. //test case
  45. /*
  46. 6
  47. micro soft microsoft hi ring hiring
  48. microsofthiring
  49.  
  50.  
  51. 11
  52. i like pep coding pepper eating mango man go in pepcoding
  53. ilikepeppereatingmangoinpepcoding
  54.  
  55. */
  56.  
Advertisement
Add Comment
Please, Sign In to add comment