HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Program to check if strings are rotations of each other or not

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
eachareprogramotherrotationscheckstringsnot

Problem

Please review my code for above problem. I tried to cover the maximum possible boundary condition. Any optimizations or new easy and fast solution are welcome.

```
public class CheckStringAreRotationalyEquals {

private static boolean areRotaionalyEquals(String s1, String s2) {
boolean areRotaionalyEquals = Boolean.FALSE;
int i = 0, j = 0;
if ((s1 == null && s2 == null)) {
areRotaionalyEquals = Boolean.TRUE;
} else {
if (s1 != null && s2 != null) {
// if both the strings are not null then check for
// are they rotaionaly equals
if (s1.isEmpty() && s2.isEmpty()) {
areRotaionalyEquals = Boolean.TRUE;
} else if (s1.length() == s2.length()) {
char ch2 = s2.charAt(j);
boolean match = Boolean.TRUE;
int count = 0;
for (i = 0; i ");
String s1 = "nullpointer";
String s2 = "ternullpoin";
boolean result = areRotaionalyEquals(s1, s2);

System.out.println(result);

s1 = "nullpointer";
s2 = "interponull";
result = areRotaionalyEquals(s1, s2);
System.out.println(result);

s1 = "nullpointer";
s2 = "rnullpointe";
result = areRotaionalyEquals(s1, s2);
System.out.println(result);

result = areRotaionalyEquals("", "");
System.out.println(result);

result = areRotaionalyEquals("", "ternullpoin");
System.out.println(result);

result = areRotaionalyEquals(null, "");
System.out.println(result);

result = areRotaionalyEquals("", null);
System.out.println(result);

result = areRotaionalyEquals(null, null);
System.out.println(result);

result = areRotaionalyEquals("hodor", "orhod");
System.out.println(result);

result = areRotaionalyEquals("sh", "hs");
System.out.pri

Solution

The code can greatly be simplified by using a different algorithm.

Note : two string are rotationally equal if the concatenation of one and itself contains the other.


"tuallyperpe" -> "tuallyperpetuallyper" contains "perpetually"

So a quick implementation would be :

public boolean rotationallyEqual(String s1, String s2) {
    if (s1 == s2) {
        return true;
    }
    if (s1 == null || s2 == null || s1.length() != s2.length()) {
        return false;
    }
    return (s1 + s1).contains(s2);
}

Code Snippets

public boolean rotationallyEqual(String s1, String s2) {
    if (s1 == s2) {
        return true;
    }
    if (s1 == null || s2 == null || s1.length() != s2.length()) {
        return false;
    }
    return (s1 + s1).contains(s2);
}

Context

StackExchange Code Review Q#163405, answer score: 7

Revisions (0)

No revisions yet.