Check if two string rotation of each other
Suppose we need to check whether string 2 is a rotation of string 1. To find this, we concatenate string 1 with string 1. Then, try to find the string 2 in concatenated string. If string 2 is present in concatenated string then, string 2 is rotation of string 1. String 2 deabc is found on the index 3 in concatenated string. So, deabc is rotation of abcde.
Example:
Input: Str1=Java, str2=Java Output: Rotation
Approach
Java
public class StringRotation {public static void main(String[] args) {String str1 = "Java", str2 = "Java";boolean flag = isRotation(str1, str2);if (flag) {System.out.println("Rotation");} else {System.out.println("Not a rotation");}}private static boolean isRotation(String str1, String str2) {if (str1.length() != str2.length()) {return false;} else {// Concatenate both stringstr1 = str1.concat(str1);// Check whether str2 is present in str1if (str1.indexOf(str2) != -1)return true;elsereturn false;}}}
Approach
Java
public class StringRotation {public static void main(String[] args) {String str1 = "Java", str2 = "Java";boolean flag = isRotation(str1, str2);if (flag) {System.out.println("Rotation");} else {System.out.println("Not a rotation");}}private static boolean isRotation(String s1, String s2) {return s1.length() == s2.length() && (s1 + s1).indexOf(s2) != -1;}}
No comments:
Post a Comment