Question:
How to check if strings are rotations of each other or not?

Summary:

The provided C++ code defines a class Solution with a method rotations to determine whether two given strings s1 and s2 are rotations of each other or not.


Suppose, you have two strings of equal lengths, s1 and s2. The task is to check if s2 is a rotated version of the string s1.


Solution:

class Solution

{

    public:

    //Function to check if two strings are rotations of each other or not.

    bool areRotations(string s1,string s2)

    {

        // Your code here

        // int l1= s1.length(), l2=s2.length();

        // if(l2!=l1) return 0;

        // if(s1==s2) return true;

        // int i,j=0;

        // for(i=0;i<l1;i++){

        //     if(s1[i]==s2[j]) j++;

        //     else j=0;

        // }

        // // cout<<j;

        // i=0;

        // for(j=j;j<l2;j++){

        //     // cout<<s2[j];

        //     if(s1[i]!=s2[j]) {

        //         // cout<<"stop";

        //         return 0;

        //     }

        //     i++;

        // }

        // return 1;

        if(s1==s2)

        return true;

        if(s1.size()!=s2.size())

        return false;

        s1=s1+s1;

        if(s1.find(s2)==-1)

        return false;

        return true;


    }

};


Explanation:

  • Check if the two strings (s1 and s2) are equal. If they are, return true as identical strings are considered rotations of each other.

  • If the lengths of the two strings are not equal, return false since rotations of different length strings cannot be identical.

  • Concatenate s1 with itself to create a larger string (s1 + s1).

  • Use the find function to check if s2 is a substring of the concatenated string s1 + s1.

  • If s2 is found as a substring, return true; otherwise, return false.

  • The provided code uses string concatenation and the find function to efficiently check if one string is a rotation of another. If a rotation exists, the concatenated string will contain the original string as a substring.


Suggested blogs:

>Python Error Solved: load_associated_files do not load a txt file

>Python Error Solved: pg_config executable not found

>Set up Node.js & connect to a MongoDB Database Using Node.js

>Setting up a Cloud Composer environment: Step-by-step guide

>What is microservice architecture, and why is it better than monolithic architecture?

>What is pipe in Angular?

>What makes Python 'flow' with HTML nicely as compared to PHP?

>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?

>Creating custom required rule - Laravel validation

>How to configure transfers for different accounts in stripe with laravel?


Nisha Patel

Nisha Patel

Submit
0 Answers