Check if a string can be obtained by rotating another string 2 places in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings s and t. We have to check whether we can get s by rotating t two place at any direction left or right.

So, if the input is like s = "kolkata" t = "takolka", then the output will be True as we can rotate "takolka" to the left side two times to get "kolkata".

To solve this, we will follow these steps −

  • if size of s is not same as size of t, then
    • return False
  • right_rot := blank string
  • left_rot := blank string
  • l := size of t
  • left_rot := left_rot concatenate t[from index l - 2 to end] concatenate t[from index 0 to l - 3]
  • right_rot := right_rot concatenate t[from index 2 to end] concatenate t[from index 0 to 1]
  • return true when (s is same as right_rot or s is same as left_rot) otherwise false

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(s, t):
   if (len(s) != len(t)):
      return False
   right_rot = ""
   left_rot = ""
   l = len(t)
   left_rot = (left_rot + t[l - 2:] + t[0: l - 2])
   right_rot = right_rot + t[2:] + t[0:2]
   return (s == right_rot or s == left_rot)
s = "kolkata"
t = "takolka"
print(solve(s, t))

Input

"kolkata", "takolka"

Output

True
raja
Published on 29-Dec-2020 17:37:59
Advertisements