Home » Interview Questions » String Interview Questions » A Program to check if strings are rotations of each other or not

A Program to check if strings are rotations of each other or not


()

Given two strings s1 and s2, write a function to say whether s2 is a rotation of s1 or not

Example

INPUT
s1 = “ABCDE”
s2 = “DEABC”

OUTPUT
s1 and s2 are rotations of each other
If we rotate s2 we will get s1

Algorithm

1. Concatenate s1 with s1

2. Now, if s2 is a substring of above concatenation, then s1 and s2 are rotations of each other.

C++ Program

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

bool areRotations(string s1, string s2)
{
	//Finding the length of s1 and s2
	int length1 = s1.length();
	int length2 = s2.length();
	//comcatinating two strings
	string s3 = s1+s1;
	//find function returns the position of the substring
	//If it does not find any substring it returns npos
	if (s3.find(s2) != std::string::npos)
	{
		return true;
	}
	else
	{
		return false;
	}

}
int main()
{
	string s1= "ABCDE";
	string s2 = "DEABC";
	if (areRotations(s1,s2))
	{
		cout<<"Strings are rotations of each other"<<endl;
	}
	else
	{
		cout<<"Strings are not rotations of each other"<<endl;
	}
}

Try It

 

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Longest Common Prefix using Sorting
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions