How to check if strings are rotations of each other or not?
- Both the Strings have equal lengths and consist of same characters.
- We can obtain the second string by rotating the first String around a certain character.
For example, Suppose we have two strings S1 = "HELLO", and S2 = "LOHEL". Both of them have equal lengths and have the same characters. By rotating "HELLO" three position to the left we can obtain "LOHEL". So, these Strings are rotation of each other.
In order to solve this problem, we will firstly check if the Strings are of same length. After that we will concatenate the first string with itself, then check whether the second one is present in the concatenated string or not. This is because if you join a String with itself then it actually contains all rotated versions of itself.
If the second String exists in the concatenated String, the Strings are rotations of each other. In our example, for S1="HELLO", the concatenated String will be "HELLOHELLO". As we can see, this concatenated string contains the String "LOHEL" and thus, these Strings are rotations of each other.
- Check lengths of s1 and s2 and return
falseif they are not same.
- If Strings are of equal length, store the concatenation of s1 with s1 itself in variable temp.
temp := st1+st1
- Check if temp contains s2 then, return
def checkRotation(s1, s2): temp = '' # Check if lengths of two strings are equal or not if len(s1) != len(s2): return False # storing concatenated string temp = s1 + s1 if s2 in temp: return True #returning true if 2nd string is present in concatenated string else: return False # Driver program to test the above function string1 = "HELLO" string2 = "LOHEL" if checkRotation(string1, string2): print("Given Strings are rotations of each other.") else: print("Given Strings are not rotations of each other.")
0 to n-mand inner loop runs from
0 to m-1where n is the length of the concatenated string and m is the length of string we want to check. For each iteration of the outer loop, the inner loop will run m-1 times, therefore the loop will execute for n-m*(m-1).
In this way we can check if two given Strings are rotations of each other or not.