How to check if strings can be derived from each other by circularly rotating in C++

1 Answer

0 votes
#include <string>
#include <iostream>
#include <algorithm>

bool checkDerived(std::string str1, std::string str2) {
    if (str1.length() != str2.length()) {
        return false;
    }
 
    for (int i = 0; i < str1.length(); i++) {
        // right rotation
        std::cout << "before: " << str1 << " - ";
        rotate(str1.begin(), str1.begin() + 1, str1.end());
 
        std::cout << "after: " << str1 << "\n";
        
        if (!str1.compare(str2)) { //  if (comparison == 0) -> Strings are equal
            return true;
        }
    }
 
    return false;
}
 
int main()
{
    std::string str1 = "ABCD";
    std::string str2 = "DABC";
 
    if (checkDerived(str1, str2)) {
        std::cout << "yes";
    }
    else {
        std::cout << "no";
    }
}




/*
run:

before: ABCD - after: BCDA
before: BCDA - after: CDAB
before: CDAB - after: DABC
yes

*/

 



answered Nov 27, 2023 by avibootz
...