Python3 Program to Check if strings are rotations of each other or not | Set 2
Given two strings s1 and s2, check whether s2 is a rotation of s1.Â
Examples:Â
Input : ABACD, CDABA
Output : True
Input : GEEKS, EKSGE
Output : True
We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm’s lps (longest proper prefix which is also suffix) construction, which will help in finding the longest match of the prefix of string b and suffix of string a. By which we will know the rotating point, from this point match the characters. If all the characters are matched, then it is a rotation, else not.
Below is the basic implementation of the above approach.Â
Â
Python3
def isRotation(a: str , b: str ) - > bool :
n = len (a)
m = len (b)
if (n ! = m):
return False
lps = [ 0 for _ in range (n)]
length = 0
i = 1
lps[ 0 ] = 0
while (i < n):
if (a[i] = = b[length]):
length + = 1
lps[i] = length
i + = 1
else :
if (length = = 0 ):
lps[i] = 0
i + = 1
else :
length = lps[length - 1 ]
i = 0
for k in range (lps[n - 1 ], m):
if (b[k] ! = a[i]):
return False
i + = 1
return True
if __name__ = = "__main__" :
s1 = "ABACD"
s2 = "CDABA"
print ( "1" if isRotation(s1, s2) else "0" )
|
Output:Â
Â
1
Time Complexity: O(n)Â
Auxiliary Space: O(n)
Please refer complete article on Check if strings are rotations of each other or not | Set 2 for more details!
Last Updated :
24 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...