Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check whether 2 strings are rotations to each other ?

Given 2 strings, design a function that can check whether they are rotations to each other without making any changes on them ? The return value is boolean.

e.g ABCD, ABDC, they are not rotations. return false

ABCD, CDAB or DABC are rotations. return true.

My solution:

shift one of them to right or left one position and then compare them at each iteration. If they are not equal at all iterations, return false. Otherwise, return true.

It is O(n). Are there other more efficient solutions ? What if the contents of them cannot be changed ?

thanks

like image 734
user1002288 Avatar asked Dec 07 '25 08:12

user1002288


1 Answers

  1. Concatenate the given string with the given string.

  2. Search for the target string in the concatenated string.

Example:

Given = CDAB

After step 1, Concatenated = CDABCDAB

After step 2, Success CDABCDAB
                        ^^^^
like image 161
Arun Avatar answered Dec 08 '25 20:12

Arun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!