Problem Statement:
Given 2 strings str1 and str2, you need to write a program to check if s2 is a rotation of s1.
Example
str1 = ABCD
str2 = CDAB
Output: true
Solution
Solution is very simple, we will concatenate the first string with itself. Then we will check if the second string is present in the concatenated string or not.
For HELLO, string concatenation is HELLOHELLO. If str2 = LOHEL, then the substring is present.
Solution in C++
#include <vector>
#include <algorithm>
//visit www.ProDeveloperTutorial.com for 450+ solved questions
#include <iostream>
#include <string>
using namespace std;
bool check_if_rotated_string(string str1, string str2)
{
if(str1.length() != str2.length())
return false;
string con_str = str1 + str1;
if(con_str.find(str2) != string::npos)
{
return true;
} else
{
return false;
}
}
int main() {
string str1 = "HELLO";
string str2 = "LOHEL";
if(check_if_rotated_string(str1, str2))
{
cout << "TRUE";
} else
{
cout << "FALSE";
}
return 0;
}
Output:
TRUE