Check if strings are rotations of each other or not in java

Check if strings are rotations of each other or not

Given two strings s1 and s2. The task is to check if s2 is a rotated version of the string s1. The characters in the strings are in lowercase.

Example 1:

Input: geeksforgeeks forgeeksgeeks Output: 1 Explanation: s1 is geeksforgeeks, s2 is forgeeksgeeks. Clearly, s2 is a rotated version of s1 as s2 can be obtained by left-rotating s1 by 5 units.

Example 2:

Input: mightandmagic andmagicmigth Output: 0 Explanation: Here with any amount of rotation s2 cant be obtained by s1.

Your Task:
Input 2 strings in different lines and complete the above given task.

Expected Time Complexity: O(N).
Expected Space Complexity: O(N).
Note: N = |s1|.

Constraints:
1 <= |s1|, |s2| <= 107

Solution of Check if strings are rotations of each other or not:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      String s1 = sc.next();
      String s2 = sc.next();

      if (s1.length() != s2.length())
      {
        System.out.print(0);
        return;
      }

        String temp = s1 + s1; //storing concatenated string

        if (temp.indexOf(s2) != -1) {
            System.out.print(1); //returning true if 2nd string is present in concatenated string
        } else {
            System.out.print(0);
        }

	}
}

Add a Comment

Your email address will not be published. Required fields are marked *