Write a program in Java to check if a string can be obtained by rotating another string by 2 places


Suppose we’ve two strings ‘a’ and ‘b’, the task is to find whether we can obtain string ‘b’ by rotating string ‘a’ exactly by 2 places in an anticlockwise or clockwise direction. For example,

Input-1

a = google
b = legoog

Output

True

Explanation − String ‘google’ can be rotated in an anticlockwise direction by two places, which results in the string ‘legoog’. Thus, we return True.

Input-2

a = tuorialst
b = tutorials

Output

False

Explanation − String ‘tuorialst’ cannot be rotated by two places in any direction to get another string ‘tutorials’. Thus, we return False.

The approach used to solve this problem

For the given two string, we have two cases in this approach −

  • For Anticlockwise rotation

  • For Clockwise rotation.

Firstly, if the length of both strings is different, then return false; otherwise, if the length of both strings is less than or equal to ‘2’, then we will return True.

In other cases, we will check if a substring of string ‘b’ by rotating two places anticlockwise becomes equal to string ‘a’, then we will return True. Otherwise, False.

Similarly, if by rotating string ‘b’ in a clockwise direction by two places, it becomes equal to string ‘a’, then return True, otherwise, we will return false.

  • Take two Input strings ‘a’ and ‘b’

  • A Boolean function checkRotated(string a, string b) takes two strings ‘a’ and string ‘b’ and returns if they are equal by rotating string ‘b’ in an anticlockwise or clockwise direction.

  • Check the length of the string ‘a’ and string ‘b’.

  • Find the substring of string ‘b’ by rotating two places in anticlockwise.

  • Now check if the resultant substring is equal to string ‘a’ or not and return true if it equals.

  • Find the substring of string ‘b’ by rotating it in two places in a clockwise direction.

  • Now check if the resultant substring is equal to string ‘a’ or not and return true if it equals.

  • If the strings are not equal, then return false.

Example

 Live Demo

public class Solution{
   static boolean checkRotated(String str1, String str2){
      String s1="";
      String s2="";
      int len= str2.length();
      if (str1.length() != str2.length())
         return false;
      s1= str2.substring(len-2, len)+ str2.substring(0,len-2);
      s2= str2.substring(0,2) + str2.substring(0,2);
      return (str1.equals(s1) || str1.equals(s2));
   }
   public static void main(String[] args){
      String s1= "google";
      String s2= "legoog";
      System.out.println(checkRotated(s1,s2) ? "True":"False");
   }
}

Output

If we will run the above code, it will print the output as,

False

Since the output of the above code is “True”, it will print ‘True’.

Updated on: 05-Feb-2021

724 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements