Given two strings s1 and s2, write a snippet to check whether s2 is a rotation of s1. Strings may contain duplicates.
Input : s1 = "ABCD", s2 = "CDAB" Output : True String s1 is rotation of s2. Input : s1 = "ABAD", s2 = "ADAB" Output : True Input : s1 = ABCD, and s2 = ACBD Output : False
One simple solution is to search first occurrence of s1 in s2. For every match, check if remaining string matches circularly.
An efficient solution is to concatenate s1 with itself. s2 is a rotation of s1 if and only if it is a substring of the rotated string. In java we can either use string contains or indexOf to check for substring.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Java Program for Reversal algorithm for array rotation
- Java Program for Program for array rotation
- Check if a given string is a valid number (Integer or Floating Point) in Java
- Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)
- Check if a string contains only alphabets in Java using Lambda expression
- Check if a string contains only alphabets in Java using ASCII values
- Check if a string contains only alphabets in Java using Regex
- Check if a String starts with any of the given prefixes in Java
- Java program to check whether a string is a Palindrome
- Program to check if the String is Null in Java
- Program to check if the String is Empty in Java
- Program to check if a String in Java contains only whitespaces
- How to check if string contains only digits in Java
- Check if a string contains only alphabets in Java
- Check if a given string is Pangram in Java
- String Literal Vs String Object in Java
- Insert a String into another String in Java
- Convert Set of String to Array of String in Java
- Convert a Set of String to a comma separated String in Java
- Convert an ArrayList of String to a String array in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.