Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
string
communitycreator

How to check if strings are rotations of each other in Java

abhilash

Problem overview

Given two strings, s1 and s2, check if s1 and s2 are rotations of each other. The rotation is in the clockwise direction.

Example

s1 = "helloeducative"
s2 = "educativehello"

Here, s2 is the rotated version of s1.

Solution

The first condition to check is whether the two strings are of the same length. If the strings are of different lengths, then we can easily say the two strings are not rotations of each other.

The next steps of the algorithm are as follows:

  1. Concatenate one of the strings to itself.
  2. Check if the other string is there in the concatenated version of the string from Step 1.
%0 node_1630674844256 h node_1 e node_2 l node_3 l node_1630674571676 o node_1630674593737 e node_1630674621923 d node_1630674574266 u node_1630674602017 c node_1630674549533 a node_1630674620082 t node_1630674600127 i node_1630674657806 v node_1630674616831 e node_1630674604410 h node_1630674577421 e node_1630674608714 l node_1630674620553 l node_1630674608465 o node_1630674661999 e node_1630674655567 d node_1630674650709 u node_1630674712459 c node_1630674651414 a node_1630674636740 t node_1630674703124 i node_1630674738223 v node_1630674674271 e

In the image above, s1 is concatenated to itself and we can find s2 in the concatenated string of s1.

public class Main{

    public static boolean check(String s1, String s2) {
        if (s1.length() != s2.length()) return false;
        String concatenatedString = s1 + s1;
        return concatenatedString.contains(s2);
    }

    public static void main(String[] args) {
        String s1 = "helloeducative";
        String s2 = "educativehello";
        boolean flag = check(s1, s2);
        if(flag) System.out.println(s1 + " and " + s2 + " are rotation of each other");
        else System.out.println(s1 + " and " + s2 + " are not rotation of each other");
    }
}

RELATED TAGS

java
string
communitycreator
RELATED COURSES

View all Courses

Keep Exploring