Question:
Check if strings are rotations of each other or not with Java

Summary: Suppose we have 2 strings of n alphabets. Through the below code, we are going to find out whether the second string, i.e. S2 is the rotation of the elements provided in string S1 or not.


Solution:

class Solution

{

    //Function to check if two strings are rotations of each other or not.

    public static boolean areRotations(String s1, String s2 )

    {

        // Your code here

        

        StringBuilder temp = new StringBuilder();

       temp.append(s1);

       temp.append(s1);

       

       if(temp.lastIndexOf(s2) == -1){

                return false;

       }

       else{

           

        return true;

       }

    }

    

}


Explanation:

  1. The areRotations method takes two parameters: s1 and s2, representing the two strings to be checked for rotation.


Inside the method:

  • It creates a StringBuilder object named temp.

  • It appends the first string s1 to temp twice, effectively creating a string that contains all possible rotations of s1.

  • It checks if s2 exists within the concatenated string using the lastIndexOf method of StringBuilder. If s2 is not found (lastIndexOf returns -1), it means s2 is not a rotation of s1, so the method returns false.

  • If s2 is found within the concatenated string, it means s2 is a rotation of s1, so the method returns true.


  1. The class Solution encapsulates this functionality, allowing users to check if two strings are rotations of each other using the areRotations method.


Answered by: >dip20sur

Credit: >GeekforGeeks


Suggested blogs:

>Python Error Solved: load_associated_files do not load a txt file

>Python Error Solved: pg_config executable not found

>Set up Node.js & connect to a MongoDB Database Using Node.js

>Setting up a Cloud Composer environment: Step-by-step guide

>What is microservice architecture, and why is it better than monolithic architecture?

>What is pipe in Angular?

>What makes Python 'flow' with HTML nicely as compared to PHP?

>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?

>Creating custom required rule - Laravel validation

>How to configure transfers for different accounts in stripe with laravel?


Submit
0 Answers