Rotate String in Python


Suppose we have two strings, A and B. We will rotate the string A and check whether it matches with B at any position of rotating, if so then return true, otherwise false. For example, if A = 'abcde', and B = 'bcdea' So answer will be true, as A can be converted to B after rotating it.

To solve this, we will follow these steps −

  • When both A and B are empty, then return true, when both are of different length then return false
  • A := concatenate A after A
  • i := 0, and j := 0
  • while i < length of A
    • if length of A – i + 1 < length of B, then return false
    • while i < length of A and j < length of B and A[i] = B[j]
      • increase i and j by 1
    • if j = length of B then returns true
    • if j is not 0, then decrease i by 1
    • j := 0
    • increase i by 1

Example

Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def rotateString(self, A, B):
      if not A and not B:
         return True
      if len(A) != len(B):
         return False
      A = A*2
      i = 0
      j=0
      #print(A,B)
      while i < len(A):
         if len(A)-i+1<len(B):
            return False
         while i<len(A) and j < len(B) and A[i] == B[j]:
            #print("Here!",i,j)
            i+=1
            j+=1
         if j == len(B):
            return True
         if j:
            i-=1
         j=0
         i+=1
ob1 = Solution()
print(ob1.rotateString("abcde", "cdeab"))

Input

"abcde"
"cdeab"

Output

True

Updated on: 28-Apr-2020

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements