code.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334
  1. /* Create a left rotation and a right rotation function
  2. * that returns all the left rotations and right rotations of a string.
  3. * leftRotations("abc") ➞ ["abc", "bca", "cab"]
  4. * rightRotations("abc") ➞ ["abc", "cab", "bca"]
  5. */
  6. // left rotation takes the front character and adds it to the back
  7. std::vector<std::string> leftRotations(std::string str) {
  8. std::vector<std::string> result = {str};
  9. // function will run for the length of a string
  10. for(int i = 0;i<str.size()-1; i++){
  11. // access first character, add to end of string
  12. str.push_back(str[0]);
  13. // access first character, remove it from string
  14. str.erase(str.begin());
  15. // now that string has been modified, add to result
  16. result.push_back(str);
  17. }
  18. return result;
  19. }
  20. // right rotation takes the back character and adds it to the front
  21. std::vector<std::string> rightRotations(std::string str) {
  22. std::vector<std::string> result = {str};
  23. int end = str.size()-1;
  24. // function will run for the length of a string
  25. for(int i = 0;i<end; i++){
  26. // access last character, add to begin of string
  27. str.insert(str.begin(),str[end]);
  28. // access last character, remove it from string
  29. str.erase(str.end()-1);
  30. // now that string has been modified, add to result
  31. result.push_back(str);
  32. }
  33. return result;
  34. }