This is the Java Program to Determine if 2 Strings are Cyclic Permutations of Each Other.
Given two different strings of the same length, find out if they are cyclic permutations of each other, that is one string can be transformed into another, by cyclically rotating its elements.
Example:
String str =”ABCD”;
String str2 = “CDAB”;
Output = “Yes”
Concatenate any one of the string to itself, let the concatenated string be str3. Now, check whether the other string is a substring of str3, if it is then str and str2 are cyclic permutations of one another, otherwise they aren’t.
Here is the source code of the Java Program to Determine if 2 Strings are Cyclic Permutations of Each Other. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
// Java Program to Determine if 2 Strings are Cyclic Permutations of Each Other
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StringRotation {
// Function to read input and display the output
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter the string");
try {
str = br.readLine();
} catch (Exception e) {
System.out.println("An I/O error occurred");
return;
}
String str2;
System.out.println("Enter the second string");
try {
str2 = br.readLine();
} catch (Exception e) {
System.out.println("An I/O error occurred");
return;
}
if(str.length() != str2.length())
{
System.out.println("\nNo");
return;
}
String str1=str;
str1 += str;
if(str1.indexOf(str2)!=-1)
{
System.out.println("\nYes");
}
else{
System.out.println("\nNo");
}
}
}
1. In main() function, firstly both the strings are entered.
2. Then the lengths of the two string are compared if they are unequal then No is displayed.
3. Otherwise, the first string is concatenated with itself and stored in the variable in str1.
4. Now, it is checked whether the second string is a subset of str1 using the command str1.indexOf(str2).
5. If the condition is true, then Yes is displayed, otherwise, No is displayed.
Time Complexity: O(1).
Case 1 (Positive Test Case): Enter the string ABCD Enter the second string CDAB Yes Case 2 (Negative Test Case): Enter the string ABCD Enter the second string DCAB No Case 3 (Positive Test Case - another example): Enter the string XYZ Enter the second string ZXY Yes
Sanfoundry Global Education & Learning Series – Java Programs.
- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Buy Java Books
- Buy Programming Books
- Practice Information Technology MCQs
- Apply for Information Technology Internship
- Practice BCA MCQs