Open In App

PHP Program to check if strings are rotations of each other or not

Last Updated : 22 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false)

Algorithm:

areRotations(str1, str2):
1. Create a temp string and store concatenation of str1 to str1 in temp. temp = str1.str1 2. If str2 is a substring of temp then str1 and str2 are rotations of each other. Example: str1 = "ABACD" str2 = "CDABA" temp = str1.str1 = "ABACDABACD" Since str2 is a substring of temp, str1 and str2 are rotations of each other.

Below is the implementation of above approach:

PHP
<?php
// PHP program to check if 
// two given strings are 
// rotations of each other

/* Function checks if passed 
strings (str1 and str2) are 
rotations of each other */
function areRotations($str1, $str2)
{
    /* Check if sizes of two
       strings are same */
    if (strlen($str1) != strlen($str2))
    {
        return false;
    }

    // Concatenate str1 with itself
    $temp = $str1 . $str1; 

    // Check if str2 is a substring of temp
    if (strpos($temp, $str2) !== false)
    {
        return true;
    }
    else
    {
        return false;
    }
}

// Driver code
$str1 = "AACD";
$str2 = "ACDA";
if (areRotations($str1, $str2))
{
    echo "Strings are rotations " . 
                  "of each other";
}
else
{
    echo "Strings are not " . 
         "rotations of each other" ;
}

// This code is contributed
// by Shivi_Aggarwal.
?>

Output
Strings are rotations of each other

Complexity Analysis:

  • Time Complexity: O(n*n), where n is the length of the string.
  • Auxiliary Space: O(n)


Next Article
Practice Tags :

Similar Reads