strings are rotations of each other

Given two strings s1 and s2. The task is to check if s2 is a rotated version of the string s1. The characters in the strings are in lowercase.

 



Example 1:

Input:
codemummy
ummycodem
Output: 
1
Explanation: s1 is codemummy, s2 is
ummycodem . Clearly, s2 is a rotated
version of s1 as s2 can be obtained by
left-rotating s1 by 5 units.
 
Example 2:

Input:
mightandmagic
andmagicmigth
Output: 
0
Explanation: Here with any amount of
rotation s2 can't be obtained by s1.

 



method 1:

Step 1: Create a temp string and store concatenation of s1 to s1 in temp.
             temp = s1.s1
Step 2: If s2 is a substring of temp then s1 and s2 are
            rotations of each other.

implementation in c++:

bool areRotations(string s1,string s2)
{ 
   if(s1.length()!=s2.length())
   return 0;
   
   string temp=s1+s1;
   
   if(temp.find(s2)!=string::npos)  //checks if s2 is a substring of temp
   return 1;
   else 
   return 0;
}


implementation in python 3:

def areRotations(s1,s2):
    s=s1+s1
    '''adding the string allows to check for all cyclic rotations as
        every rotation is one of the strings of the double string'''
        
    if(len(s1)==len(s2) and s2 in s):
        return 1
    return 0



No comments

darkmode