String Rotation
Given two strings(S1 and S2), write a program to determine if a string S2 is a rotation of another string S1.
Input
The first line of the input will be a string S1.
The second line of the input will be a string S2.
Output
If string S2 is a rotation of another string S1, print number of right rotations made by string S1 to match the string S2. Otherwise, print "No Match".
Where right rotation means all elements are moving towards the right side by one place where the last element will be placed in the first place example, one right rotation of "python" is "npytho".
Explanation
For example, if the given strings S1 and S2 are "python" and "onpyth",
The first right rotation of s1 is "npytho" which is not equal to string S2"onpyth"
The second right rotation of s2 is "onpyth" which is equal to string S2 "onpyth".
So the output should be 2
Sample Input 1
python
onpyth
Sample Output 1
2
def checkStringRotations(str1, str2):
number_of_rotations=numberOfRotations(str1,str2)
if number_of_rotations==-1:
print("No Match")
else:
print(str(number_of_rotations))
#Function that returns the number of rotations
def numberOfRotations(str1,str2):
t=str1
number_of_rotations =0
while t !=str2:
number_of_rotations+=1
t = str1[len(str1) - number_of_rotations:] + str1[0 : len(str1) - number_of_rotations]
if number_of_rotations>=len(str1):
return -1
return number_of_rotations
print("Sample Input 1")
print("python")
print("onpyth")
print("Sample output 1")
checkStringRotations("python", "onpyth")
Comments
Leave a comment