Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

Monday, May 29, 2023

2 Ways to Check if a String is Rotation of Other in Java? Example

To check if one string is a rotation of another string in Java, you can use the following two approaches: 

 Approach 1: Concatenation and Substring Comparison Concatenate the first string with itself. Check if the second string is a substring of the concatenated string. If it is, then the second string is a rotation of the first string. Here's an example implementation using this approach:


public static boolean isRotation(String str1, String str2) {
    // Check if the lengths of both strings are equal
    if (str1.length() != str2.length()) {
        return false;
    }

    // Concatenate the first string with itself
    String concatenated = str1 + str1;

    // Check if the second string is a substring of the concatenated string
    return concatenated.contains(str2);
}

Example usage:


String str1 = "hello";
String str2 = "llohe";
boolean isRotation = isRotation(str1, str2);
System.out.println(isRotation);
// Output: true


Approach 2: Rotation Point Comparison Find the rotation point in the first string by comparing it with the second string. 

Check if the substring of the first string from the rotation point onwards is equal to the substring of the second string from index 0 to the remaining characters. 

If it is, then the second string is a rotation of the first string. Here's an example implementation using this approach:


public static boolean isRotation(String str1, String str2) {
    // Check if the lengths of both strings are equal
    if (str1.length() != str2.length()) {
        return false;
    }

    int rotationPoint = -1;

    // Find the rotation point in the first string
    for (int i = 0; i < str1.length(); i++) {
        if (str1.charAt(i) == str2.charAt(0)) {
            rotationPoint = i;
            break;
        }
    }

    // Check if the rotation point is found and the substrings match
    return rotationPoint != -1 && str1.substring(rotationPoint).equals(str2.substring(0, str1.length() - rotationPoint));
}

Example usage:


String str1 = "hello";
String str2 = "llohe";
boolean isRotation = isRotation(str1, str2);
System.out.println(isRotation);
// Output: true

Both approaches can determine whether one string is a rotation of another string in Java. You can choose the approach that best suits your requirements and preferences.