12345678910111213141516171819202122232425262728293031323334 |
- /* Create a left rotation and a right rotation function
- * that returns all the left rotations and right rotations of a string.
- * leftRotations("abc") ➞ ["abc", "bca", "cab"]
- * rightRotations("abc") ➞ ["abc", "cab", "bca"]
- */
- // left rotation takes the front character and adds it to the back
- std::vector<std::string> leftRotations(std::string str) {
- std::vector<std::string> result = {str};
- // function will run for the length of a string
- for(int i = 0;i<str.size()-1; i++){
- // access first character, add to end of string
- str.push_back(str[0]);
- // access first character, remove it from string
- str.erase(str.begin());
- // now that string has been modified, add to result
- result.push_back(str);
- }
- return result;
- }
- // right rotation takes the back character and adds it to the front
- std::vector<std::string> rightRotations(std::string str) {
- std::vector<std::string> result = {str};
- int end = str.size()-1;
- // function will run for the length of a string
- for(int i = 0;i<end; i++){
- // access last character, add to begin of string
- str.insert(str.begin(),str[end]);
- // access last character, remove it from string
- str.erase(str.end()-1);
- // now that string has been modified, add to result
- result.push_back(str);
- }
- return result;
- }
|