Friday, June 18, 2021
Home coding Write a program to check given string is rotation of each other.

Write a program to check given string is rotation of each other.

Given two string s1 and s2 we have to find that whether the first string is rotation of another string.

Example:

input: s1:XXYZ  s2:XYZX
output:both string are rotation of each other

input: s1:xysds s2:psdwd
output:both string are not rotation of each other.

Logic:

Step 1: create a temporaray string .
step 2: assign the value ,temp_string= string1+string1;
step 3:here we will use find function of string to check whether string2 is present in temp string or not.
step 4:if it is present then it is rotation of eacg other.
# include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 
string s1 = "MMNP", s2 = "MNPM"; 
if(s1.length()!=s2.length())
{
   cout<<"string are not rotation of each other"<<endl;
}
else
{
    string s3=s1+s1;
    if(s3.find(s2)!=string::npos)//here we are checking in s3 ,is s2 present or not 
    {
        cout<<"string are rotation of each other"<<endl;
    }
    else
    {
        cout<<"string are not rotation of each other"<<endl;
    }
}

} 

Output:

string are rotation of each other

Time Complexity:O(N)

space complexity:O(N)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments