Thursday 24 September 2015

Rotate a string to make another

Problem

Given two string find whether one string can be formed by rotating another string.

Solution

Suppose string b is to be formed by rotating string a. We concatenate string a with string a. then find for substring b in that concatenation.

Code

public class RotateString
{
 public static void main(String[] args)
 {
  String string1 = "rotation";
  String string2 = "tionrota";
  System.out.println(isRotationPossible(string1, string2));
 }

 private static boolean isRotationPossible(String string1, String string2)
 {
  String str = string1 + string1;
  return str.contains(string2) && string1.length() == string2.length();
 }

}

No comments:

Post a Comment