How to check if a string can be rotating another string by two places in C++

2 Answers

0 votes
#include <string>
#include <iostream>
  
bool isRotated(std::string str1,std::string str2) {
    if (str1.length() != str2.length())
        return false;
          
    if (str1.length() < 2) {
      return str1.compare(str2) == 0;
    }
  
    int lenstr2 = str2.length();
   
    std::string left_rotation = str2.substr(2) + str2.substr(0, 2) ; 
   
    std::string right_rotation = str2.substr(lenstr2 - 2, 2) + str2.substr(0, lenstr2 - 2);
                      
    std::cout << left_rotation << "\n";             
    std::cout << right_rotation << "\n";             
   
    return (str1.compare(left_rotation) == 0 || str1.compare(right_rotation) == 0);
}
   
int main()
{
    std::string str1 = "ExMachina";
    std::string str2 = "MachinaEx";
   
    if (isRotated(str1, str2)) {
        std::cout << "yes";
    }
    else {
        std::cout << "no";
    }
}
  
  
  
  
/*
run:
  
chinaExMa
ExMachina
yes
  
*/

 



answered Nov 27, 2023 by avibootz
edited Nov 28, 2023 by avibootz
0 votes
#include <string>
#include <iostream>
#include <algorithm>
  
bool isRotated(std::string str1,std::string str2) {
    if (str1.length() != str2.length())
        return false;
          
    if (str1.length() < 2) {
      return str1.compare(str2) == 0;
    }

    std::string left_rotation = str2;
    rotate(left_rotation.begin(), left_rotation.begin() + 2, left_rotation.end());
   
    std::string right_rotation = str2;
    rotate(right_rotation.rbegin(), right_rotation.rbegin() + 2, right_rotation.rend());
 
    std::cout << left_rotation << "\n";             
    std::cout << right_rotation << "\n";             
   
    return (str1.compare(left_rotation) == 0 || str1.compare(right_rotation) == 0);
}
   
int main()
{
    std::string str1 = "ExMachina";
    std::string str2 = "MachinaEx";
   
    if (isRotated(str1, str2)) {
        std::cout << "yes";
    }
    else {
        std::cout << "no";
    }
}
  
  
  
  
/*
run:
  
chinaExMa
ExMachina
yes
  
*/

 



answered Nov 27, 2023 by avibootz
edited Nov 28, 2023 by avibootz

Related questions

...