DG

dhirendra_gupta

Student at BIT Mesra July 27, 2020, 3:11 p.m. ⋅ 199 views

Check if strings are rotations of each other or not


Given a string s1 and another string s2 your task is to check if s2 is rotation of s1 or not. Print Yes, if it is a rotation otherwise print No.

Example

s1 = "ABCD"

s2 = "CDAB"

Output

Yes

Example 2

s1 = "ABCD"

s2 = "ACDB"

Output

No

Solution

In order to check if any given string is rotation or not, we can simply append our current string to itself again and check if the given string is substring of this appended string or not.

So, if we were to solve above example it would be like this:

tempString = s1 + s1

so, tempString would become, "ABCDABCD"

Now, since, s2 = "CDAB" is a substring of tempString we will print Yes. While, s2 = "ACDB" is not a substring of tempString, we'll print No.

Let's implement this approach.

 

// C++ program to check if two given strings are rotations of  each other 

#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
    string str1 = "ABCD", str2 = "CDAB"; 


    if (str1.length() != str2.length())
    {
        
	    cout<<"No";
    }

    else 
    {
        string temp = str1 + str1; 
        if (temp.find(str2) != string::npos)
        {
            cout<<"Yes";
        }
        else
        {
            cout<<"No";
        }
        
    }

return 0; 
} 
Yes

 



Go back to feed

HackersFriend Updates





View more


Events


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details


Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details