Advertisement
Guest User

Untitled

a guest
Oct 26th, 2021
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. using namespace std;
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5.  
  6. // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words,
  7. // determine if s can be segmented into a space-separated sequence of one or more dictionary words.
  8.  
  9. class SpaceSeparatedSequence
  10. {
  11. public:
  12.   static bool canBeSeparated(string s, vector<string> wordDict)
  13.   {
  14.     // Start of the test word
  15.     int index1 = 0;
  16.     // End of the test word
  17.     int index2 = 0 + 1;
  18.     // Until we have reached the end of the word
  19.     while (index1 < s.size() - 1)
  20.     {
  21.       // If we haven't foudn a word for teh rest of rht string, return false
  22.       if (index2 >= s.size()) {
  23.         return false;
  24.       }
  25.       // The substring to check
  26.       string testString = s.substr(index1, index2 + 1 - index1);
  27.       //Check each word in the dictionary
  28.       for (auto dictWord : wordDict)
  29.       {
  30.         // If the substring is in the dictionary
  31.         if (dictWord == testString)
  32.         {
  33.           // Move the end of the string
  34.           index1 = index2 + 1;
  35.           index2 = index1 + 1;
  36.           break;
  37.         }
  38.       }
  39.       index2++;
  40.     }
  41.     if (index1 == s.size())
  42.     {
  43.       return true;
  44.     }
  45.     else
  46.     {
  47.       return false;
  48.     }
  49.   }
  50. };
  51.  
  52. int main()
  53. {
  54.   // One test where the program should succeed
  55.   string input = "testingthisstring";
  56.   vector<string> wordDict = {"testing", "hello", "world", "this", "string"};
  57.   cout << SpaceSeparatedSequence::canBeSeparated(input, wordDict) << endl;
  58.  
  59.   // One test where it should succeed out of order
  60.   input = "worldhello";
  61.   wordDict = {"testing", "hello", "world", "this", "string"};
  62.   cout << SpaceSeparatedSequence::canBeSeparated(input, wordDict) << endl;
  63.  
  64.   // One test where it should fail
  65.   input = "trytotestthisstring";
  66.   wordDict = {"testing", "hello", "world", "this", "string"};
  67.   cout << SpaceSeparatedSequence::canBeSeparated(input, wordDict) << endl;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement