📌  相关文章
📜  https:www.geeksforgeeks.org a-program-to-check-if-strings-are-rotations-of-each-other (1)

📅  最后修改于: 2023-12-03 15:15:45.707000             🧑  作者: Mango

A Program to Check if Strings are Rotations of Each Other

Introduction

This program checks whether two given strings are rotations of each other or not. Rotating a string means moving its characters one by one to the left or right and then putting the left/rightmost character at the end/beginning respectively.

Example

For example, ABCD will be rotated to BCDA, CDAB, DABC, and back to ABCD, while ACBD cannot be formed by rotating ABCD.

Solution

The idea of the solution is to concatenate one of the strings with itself, so that all possible rotations of the original string can be found in the concatenated string. The concatenated string can then be searched for the other string.

Here is the code in C++:

#include <iostream>
#include <string>

using namespace std;

bool areRotations(string str1, string str2) {
    if (str1.length() != str2.length()) {
        return false;
    }
    string concat = str1 + str1;
    return (concat.find(str2) != string::npos);
}

int main() {
    string str1 = "ABCD";
    string str2 = "CDAB";
    if (areRotations(str1, str2)) {
        cout << "Strings are rotations of each other" << endl;
    } else {
        cout << "Strings are not rotations of each other" << endl;
    }
    return 0;
}
Conclusion

This program can help you easily check whether two strings are rotations of each other. It is a simple and efficient solution that can be easily implemented in any programming language that supports string concatenation and finding substrings.