Description
Given two string s1 and s2 then write a java program to check if s1 is the rotation of another string s2.Here rotation means, each character of s2 must be the same character of s1 but only thing is that the character in s2 can be present at any random position. Following is the java program to check if a given string is a rotation of another string.
package com.devglan.set1; import java.util.Arrays; public class StringRotation { public boolean checkStringRotation(String s1,String s2){ char[] c1 = s1.toCharArray(); char[] c2 = s2.toCharArray(); Arrays.sort(c1); Arrays.sort(c2); boolean rotation = false; if(Arrays.equals(c1, c2)){ System.out.println("s2 is a rotated version of s1"); rotation = true; }else{ System.out.println("s2 is not rotated version of s1."); } return rotation; } public static void main(String[] args){ StringRotation rotation = new StringRotation(); rotation.checkStringRotation("checkStringRotation", "RotationcheckString"); //rotation.checkStringRotation_OtherWay("checkStringRotation", "StringRotationcheck"); }
Arrays.sort() is an implicit method provided by java. Once both the array is sorted and if given string is a rotation of another, then the array must be equal.
Another way to check for string rotation is by using contains() method. Following is the implementation.
public boolean checkStringRotation_OtherWay(String s1,String s2){ boolean rotation = false; if(s1.length() != s2.length()) { System.out.println("s2 is not rotated version of s1"); } else { String s3 = s1 + s1; if (s3.contains(s2)) { System.out.println("s2 is a rotated version of s1"); rotation = true; } else { System.out.println("s2 is not rotated version of s1"); } } return rotation; }