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


StringViews 3114

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

 

 

Translate ยป